Reputation: 6894
i use the below code to dynamically load js scripts
$.getScript("/../../site/js/test.js").done(function(script, textStatus) {
console.log("test.js :: " + textStatus );
});
What should i do if i want to load multiple scripts files in same piece of code instead of writing another getScript .. example test2.js , test3,js
Upvotes: 2
Views: 9323
Reputation: 3757
This is the best way to load js files async.
loadScripts(['script1.js','script2.js'], function(){ alert('scripts loaded'); }
function loadScripts(scripts, callback){
var scripts = scripts || new Array();
var callback = callback || function(){};
for(var i = 0; i < scripts.length; i++){
(function(i) {
$.getScript(scripts[i], function() {
if(i + 1 == scripts.length){
callback();
}
});
})(i);
}
}
Upvotes: 1
Reputation: 61
// multiple browser compatible and deoesnt load same script twice.
var filesadded = ""
function loadJSQueue(array, success) {
if (array.length != 0) {
if (filesadded.indexOf("[" + array[0] + "]") == -1) {
filesadded += "[" + array[0] + "]" //List of files added in the form "[filename1],[filename2],etc"
var callbackCalled = false;
oHead = document.getElementsByTagName("head")[0] || document.documentElement;
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = array[0];
array.shift(); // $(oScript).ready(function () { // // }) // oScript.onload = oScript.onreadystatechange = function () { // if (!this.readyState || this.readyState == 'complete') { // // loadJSQueue(array, success); // } // };
var done = false;
// Attach handlers for all browsers
oScript.onload = oScript.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
// jQuery.handleSuccess(null, xhr, status, data); // jQuery.handleComplete(null, xhr, status, data);
// Handle memory leak in IE
oScript.onload = oScript.onreadystatechange = null;
if (oHead && oScript.parentNode) {
oHead.removeChild(oScript);
}
loadJSQueue(array, success);
}
};
oHead.insertBefore(oScript, oHead.firstChild);
}
else {
array.shift();
loadJSQueue(array, success);
}
}
else {
success();
}
}
// usage:
loadJSQueue(["../../JavaScript/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js",
"../../JavaScript/plupload/js/plupload.js",
"../../JavaScript/plupload/js/plupload.html4.js",
"../../JavaScript/plupload/js/plupload.html5.js"
], function () {
//do your after load stuff here
})
Upvotes: 1
Reputation: 724
Well, if you're going to have to write .getScript for each file, this is a clean way to do it. It'll also allow to build a list of files to load.
var scripts = ['plugin.js', 'test.js'];
for(var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function() {
alert('script loaded');
});
}
Upvotes: 6
Reputation: 29658
I would suggest using an existing loader framework instead of writing your own. Take a look at RequireJS: http://requirejs.org/
Upvotes: 3