Have an array that holds the link to your script files and then you have two options either to use $.getScript() to load each one Or by building an HTML out of it and appending it to your head
or body
tag. I prefer head
tag to keep all the scripts and css files.
Your array of script files
var JsFiles = ["script1.js","script2.js","script3.js","script4.js"];
First approach using $.getScript()
JsFiles.each(function(i,v){
$.getScript(JsFiles[i], function( data, textStatus, jqxhr){
console.log( textStatus ); // Success
});
});
Disadvantage of the above approach is that the getScript
makes a async calls to your script files that means if the script2.js
is dependent on the script1.js
(for example if script1.js
is some plugin file which use initialize in script2.js
) Then you will face issues.
To overcome you might have to then use Promises
or write a callback on each getScript
success function which will trigger next script load and so on..
If the order of the script loading is not important then above approach is good to go.
Second approach by building HTML
var scriptTags ="";
JsFiles.each(function(i,v){
scriptTags += "<script src='"+ JsFiles[i] +"'></script>";
});
$('head').append(scriptTags);
Good thing about this approach is that the script files will now load synchronously and you will not face the dependency problem. But make sure the independent files start from first and the dependent files come at last.