I have a javascript widget that is included in a page by inserting a single script tag (as the application should be easiliy distributable):
<script type="text/javascript" src="loadMyWidget.js"></script>
loadMyWidget.js then needs to load multiple script files, which has to run in a certain sequence. I've tried to load them async by inserting script elements into the DOM, but that doesn't give me control of the sequence.
I also tried using head.js which is great for modern browsers, but I can't get it to work in IE7 and 8.
Minifying the scripts into one file is unfortunately difficult, as it is composed of a number of files from different projects and I wouldn't know when to update the script.
As simple as it seems, I need to load javascript files from javascript code in a certain sequence and get it to work in all browsers, including IE7 and 8.
Optimize Javascript Placement Place your javascript at the end of your HTML file if possible. Notice how Google analytics and other stat tracking software wants to be right before the closing </body> tag. This allows the majority of page content (like images, tables, text) to be loaded and rendered first.
By default, JavaScript runs in a single process – in both web browsers and Node. js. The so-called event loop sequentially executes tasks (pieces of code) inside that process.
If you're using jQuery.getScript() you can use it as a $.when() to hold off execution until things have stopped loading.
If by "sequential execution" you mean that you need to load the requisites before execution the following will work
$(function(){
$.when(
$.getScript("/script1"),
$.getScript("/scirpt2"),
$.getScript("/script3")
}).done(function(){
// do stuff with the contents of my new script files
});
If by sequential execution you mean that you need to execute files one after the other try this:
$.Deferred()
.then(function () { return $.getScript("/script1"); })
.then(function () { return $.getScript("/scirpt2"); })
.then(function () { return $.getScript("/script3"); })
.resolve();
Of course, this requires jQuery, which after your edits, this may not work for you.
Suggested Reading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With