Loading sequence of scripts in html - javascript

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>

Related

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);
}

JS: parse dynamically added script before other scripts

I would like to have the following on my page:
a script ("script1.js") that adds a second script ("script2.js") dynamically to the page.
a third script ("script3.js").
"script3" overwrites some of the functions in "script2", therefore the order that the scripts should be parsed is:
script1 > script2 > script3.
And the console should show: 1 2 3. Instead I see 1 3 2.
I have tried using "defer" on "script3" with no success:
HTML file:
<html>
<head>
<script src="script1.js"></script>
<script defer type='text/javascript' src="script3.js"></script>
</head>
</html>
script1.js:
console.log('1');
var head = document.getElementsByTagName('head')[0];
const url = 'script2.js';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
script2.js:
console.log('2');
script3.js:
console.log('3');
As ugly as it sounds, you could use document.write inside script1.js to load script2.js. The scripts will execute in correct order.
// script1.js
console.log('1');
document.write('<script src="script2.js"></script>');

JavaScript URL checking for pupunder

I have some javascript that checks the url is "musicmartian.com" and will then run a script that displays a pupunder ad, but doesnt seem to work.
the code is:
<script type="text/javascript">
if (window.location.href=="musicmartian.com") {
src='//go.oclaserver.com/apu.php?zoneid=540338'
}
</script>
The website is: http://musicmartian.com/ and the ad provider is PropellorAds if thats needed information.
Insert this code inside body of your html (before </body>)
<script type="text/javascript">
if (window.location.hostname === "musicmartian.com") {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//go.oclaserver.com/apu.php?zoneid=540338';
document.body.appendChild(script);
}
</script>

HTML: After Dynamic JavaScripts Loaded Completely

I am loading my JavaScript files dynamically in the page:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
</script>
</head>
<body>
</body>
</html>
I need to know when these Scripts loaded completely. Is there any workaround or code snippets to do this?
before document.body.appendChild
scrimpt1.addEventListener('load', function() { console.log('loaded'); });
obviously you'll want to do "something useful" instead of the simple console.log I've shown
BUT ... this isn't always realiable
try this
var numScripts;
function scriptLoaded() {
numScripts --;
if(numScripts == 0) {
console.log('huzzah all scripts loaded');
}
}
then, your code
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
numScripts = 3;
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
at the end of each of your scripts, put something like
if(windows.scriptLoaded) {
scriptLoaded();
}
Use a callback
function greetFinished() {
alert("Do stuff finished");
}
​function greet (greeting, callback) {
alert(greeting)
callback (options);
}
greet("Hello",greetFinished);
greetFinished will be called inside the greet function greetFinished is a callback it will be called after the alert.

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