I'm trying load some scripts dynamically with jQuery:
var scripts = ['script1.js','script2.js','script3.js'];
$.each(scripts , function(i, val) {
$.getScript(val, function() {
console.log('loaded '+ val);
});
But sometimes the order of loaded scripts changes. How can I load each script after the previous one has successfully loaded?
There's a small issue with @ngryman's solution; if there is only a single url in the array of urls to load, the .done() function's arguments param will be a single dimensional array, rather than 2 dimensional. You'll need to check arguments before looping through, thus:
Apologies for new answer, not enough rep to post as a comment on @ngryman's answer, but thought it might help someone out!
You can sort() the array -
and then use sorted in your each function.
You can load each after the previous has finished loading by using the callback function of
$.getScript()
as a recursive function call.What's occurring in your code is that the scripts are being requested at the same time and since they load asynchronously, they return and execute in random order.
Update
I haven't tested this, but if the scripts are hosted locally, then you could try to retrieve them in plain text, then store all of the code in variables until they are all loaded at which time you could evaluate the scripts in order:
You make make use of the fact the
jqXhr
object returned by$.getScript
(and all other Ajax methods) implements the Promise interface and therefore provides.pipe()
which can be used to chain deferred objects:For more information, have a look at deferred objects and
deferred.pipe
.Overall, using deferred objects gives you greater flexibility and might let you add error handlers more easily.
An enhanced version of @Jasper's solution:
$.when
to synchronize the calls.Here is the code:
This gist: https://gist.github.com/ngryman/7309432.
Some scripts could vary in size, therefore it's unpredictable. Try something like this.
This should load each script after the last one has fully loaded. Make sure you start it off by calling the function
LoadScript(0);