I need to load a variable number of javascript source files before running javascript code that depends on them. Sometimes 1 script needs to be loaded, other times 2. The ge
Loading multiple scripts by $.getScript() one after the other and do stuff after all the scripts are loaded
Working Fiddle. Check the Console window for the output
We can create a function to which we pass array of js file paths, this function will do a $.getScript()
for the first js file and on success method it will call the same function by passing the second js file index, and this on success will call the same function by passing 3rd file index and so on until it loads the last file. So its basically a recursion function which will give a callback when all the files in the array has been loaded.The end code would be as simple as
LoadAllScripts("yourArray",function(){
alert("all scripts loaded!!");
});
So the complete code would go like this.
var LoadAllScripts = function (scriptArray, callback) {
SyncLoadScript({ scriptArray: scriptArray, index: 0}, function () {
callback();
});
};
And SyncLoadScript (core of the logic
) looks like
var SyncLoadScript = function (scriptConfig, callback) {
var $this = this;
var script = scriptConfig.scriptArray[scriptConfig.index];
if (scriptConfig.scriptArray.length > scriptConfig.index) {
if (script.trim().length > 0) {
$.getScript(script, function () {
console.log(script);
SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(script + " failed while loading");
debugger;
console.log("Error: "+errorThrown);
SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
});
}
else {
console.log("invalid script src!!");
}
}
else {
callback();
}
}
Then you can make a simple call to LoadAllScripts by passing array of js file path. like below.
LoadAllScripts(["1.js","2.js","3.js","4.js"], function () {
console.log("All the scripts have been loaded.");
//do your stuff after all the scripts are loaded.
});
Note: I have given empty callbacks for you guys to make tweaks and pass around any data of choice. probably to hold all the failed scripts that you can passback to the main function and try to reload them again
.