Load Javascript file with Javascript based on URL - javascript

Can I use Javascript to load a Javascript file in HTML based on a string in URL?
For example something like this:
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1)
{
include ('javascript_deutch.js)
}
else
{
include ('javascript_english.js)
}
</script>
I cannot use any other method like PHP or something.
Thanks for the help guys.
Unfortunately none of these things seem to work.
This
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<script src="javascript_english.js"></script>';
}
</script>
ended up just displaying a message at the top of my page:
'; }else{ document.head.innerHTML+=''; }
And this
<script type="text/javascript">
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
</script>
did not request the files on the server at all.
Am I missing something?

You can create a <script> tag dynamically:
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);

The easy way without framework:
var _script = document.createElement('script');
_script.src = 'fileName.js';
document.body.appendChild(_script);
May be will be good to isolate this into separate function like this:
function includeJsFile(fileName) {
var _script = document.createElement('script');
_script.src = fileName;
document.body.appendChild(_script);
}
But may be will be good for you to check
http://requirejs.org/

Why not. Just add them in the script tags.
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<<script src="javascript_english.js"></script>';
}
</script>

Try this code, this method worked for me:
<script>
document.write('<script type="text/javascript" src="' + language-file + '.js"><\/script>')
</script>

Related

Loading sequence of scripts in html

I want to load a constants file as per the language the user has selected. For that I want to load the scripts dynamically.
<html>
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
</script>
<script type="text/javascript" src="../js/RandomScript.js"></script>
</body>
Whole code is in HTML.
When I tried the code above, RandomScript.js is loaded before the constant file.
How can I maintain sequence of loading files.
I am not using jQuery or something, so is there any way to do interpolation of src of script?
You can use onload event listener to load .js files sequentially.
First create an array of URLs of scripts. Then loop through it recursively. onload event listener ensures that the scripts are loaded sequentially.
var scriptURLs = [
"../constants.en.js",
"../js/RandomScript.js"
];
function loadScript(index){
if(index >= scriptURLs.length){
return false;
}
var el = document.createElement('script');
el.onload = function(){
console.log("Script loaded: ", scriptURLs[index]);
loadScript(index+1);
}
el.src = scriptURLs[index];
document.body.appendChild(el);
// OR
// document.head.appendChild(el);
}
loadScript(0); // Load the first script manually.
Hope this helps.
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
document.body.appendChild(jsElement);
jsElement.onload = () => {
callyournewScript();
}
jsElement.src = "../constants.en.js";
Load the ../js/RandomScript.js after loading the ../constants.en.js like following
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
var script = document.createElement("script");
script.src = "../js/RandomScript.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
</script>
<!-- <script type="text/javascript" src="../js/RandomScript.js"></script> -->
</body>

Loading a javascript dynamically in angular

I have got the following scenario and problem to solve. Any help will be appreciated.
Scenario
I have an angular application which calls a service(web api) and gets the contents back. The content is added to the html div. The content is as follow:
<script type="text/javascript" src="https://xxxx.com/ws/js/xxxxloader.js" id="theLoader"></script>
<script type="text/javascript">
// The code here look at the if the above script has been loaded properly by //checking the state of above script tag
</script>
I am adding the returned content to the HTML of the component in NgOnInit() as follow.
ngOnInit(){
this.apiService.getContent().subscribe(
d => {
this.responseString = d.toString();
var frag = document.createRange().createContextualFragment(this.responseString);
document.getElementById("theContainer").appendChild(frag);
}
);
}
However, it is failing because the first script tag (#theLoader) has never been loaded properly. I think it is because I am injecting the script tag after Dom has finished loading.
If you can see the better way of injecting the script, can you enlighten me.
Thanks in advance.
You can dynamically inject the JS URL by creating dynamic script tag
ngOnInit(){
function loadScripts(url: string){
var el = document.createElement('script');
el.onload = function(script){
console.log(script + ' loaded!');
// you can call the JS Function
};
el.src = url;
document.getElementsByTagName('body')[0].append(el);
}
</script>
ngAfterViewInit () {
this.loadScript('path to your js');
}
loadScript(url) {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
Try this one :
ngOnInit(){
this.addScripts("https://xxxx.com/ws/js/xxxxloader.js", 'text/javascript');
this.addScripts("https://xxxx.com/js/mail.js", 'text/javascript');
}
addScripts(src, type): void{
var script = document.createElement('script');
script.src = src;
script.type = type;
document.querySelector('body').appendChild(script);
}

How to include an external javascript file conditionally? [duplicate]

This question already has answers here:
Dynamically load a JavaScript file
(30 answers)
Closed 8 years ago.
I have this code:
<script src="http://external/js/file/url.js">
</script>
I want to do something like this-
<script>
if(2>1){
//include http://external/js/file/url.js
}
</script>
Any idea?
This question has been asked before in Include a Javascript File in another Javascript File.
This peice of code may fit what you have been looking for
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
if that script does not work, i suggest you to look over and read the post above: Include a Javascript File in another Javascript File.
I hope this helps, it may not be the answer you had been looking for, but it may just help.
You simply load it asynchronously like
if(yourCondition==true){
var d = document,
h = d.getElementsByTagName('head')[0],
s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://external/js/file/url.js';
h.appendChild(s);
}
You could use something like:
<script type="text/javascript">
if (condition == true) {
document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"http://external/js/file/url.js\" type=\"text/javascript\"></script>");
}
</script>

How to include a .js file in onclick button?

I was trying to make a button that will run a JavaScript when it was clicked.First, my script was like this
<script>
function myFunction()
{
alert('Invalid username or password. Please try again.')
}
</script>
<input onclick="myFunction()" type="submit" value="Generate" href="submit.php" >
It works, and a popup appear.But when I try to call JavaScript from another site, nothing happens.
<script>
function myFunction()
{
document.body.appendChild(document.createElement('script')).src='https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js';
}
</script>
<input onclick="myFunction()" type="submit" value="Generate" href="submit.php" >
You need to include the js file once event occurs.
Please refer to this link, it demonstrates dynamic including js and css.
Add html code
<ul>
<li>Load "myscript.js"</li>
<li>Load "mystyle.css"</li>
</ul>
Then js code
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
Code for myscript.js
var petname="Spotty"
alert("Pet Name: " + petname)
Code for mystyle.css
#ul li{
background-color: lightyellow;
}
Similar to this :
You can call loadjscssfile('myscript.js','js') inside your button onclick() event handler.
Update:
Try this out:
<a id='myScript' type="submit" href="submit.php" > Generate </a>
Script:
<script type="text/javascript">
var myScript = document.getElementById('myScript');
myScript.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
EDITED: The below solution might not be what you are looking for now.
I have been using this,a solution which I found from stackoverflow itself.
function loadScripts(array,callback){
var loader = function(src,handler){
var script = document.createElement("script");
script.src = src;
script.onload = script.onreadystatechange = function(){
script.onreadystatechange = script.onload = null;
handler();
}
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild( script );
};
(function(){
if(array.length!=0){
loader(array.shift(),arguments.callee);
}else{
callback && callback();
}
})();
}
This will help you create script tags.
loadScripts([
"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
"https://raw2.github.com/BlackEagleBCC/Script/master/myscript.js"
],function(){
alert('Scripts have been loaded successfully');
});
Edited:
I have used this method when I needed to build script tags and get a callback after everything loads fine. (These things come handy :) )
https://stackoverflow.com/a/1867135/3222041

Javascript Append a new Jquery file with noconflict

I need to append a new version of jquery into head section as below.
<head>
<script type="text/javascript" async="" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">var $jq = jQuery.noConflict(true);</script>
<script>
$jq(document).ready(function() {
// works well
});
</script>
</head>
It works fine when I put it directly. But my case is, I need to append it dynamically, reslove noconflict and the implementation using external javascript file (my.js). (As below)
my.js file should be consisted with the all implementation.
// insert jquery file
var jqueryfile = document.createElement('script');
jqueryfile.type = 'text/javascript';
jqueryfile.async = true;
jqueryfile.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(jqueryfile, s);
How to do my implementation with jQuery.noConflict() and $jq(document).ready(function() {}).
Thank you!
You can try this to insert script in HEAD section
head1=document.getElementsByTagName("head")[0];
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.innerHTML="var $jq = jQuery.noConflict(true);
$jq(document).ready(function() {
// works well
});
";
head1.appendChild(s);
head1.appendChild(s1);
you only need to include a regular js file in the regular fashion like so and alias jQuery as a parameter, freeing up the dollar sign:
<script type="text/javascript">js/scripts.js</script>
and then add this to your scripts.js file:
;(function ( $ ) {
// all code in this anonymous function will not conflict with any other library
// and it will never get in to the global namespace which is good
$(document).ready(function() {
// works well
});
})( jQuery );
now you can just use the "$" for jQuery freely

Categories