When we do dynamic insertion for javascript, sometimes order matters. We sometimes solve this by using onload property; however, if there are many external javascripts, and those scripts has to be loaded in order, then what should we do?
I solved this problem by recursively defined onload functions; however not so sure about efficiency... since this is a script, I think it does lazy eval.... Any help?
//recursively create external javascript loading chain
//cautiously add url list according to the loading order
//this function takes a list of urls of external javascript
function loadScript(url) {
if( url.length == 0) {
//final function to execute
return FUNCTION;
}
var f = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url.pop();
//recursion
script.onload = loadScript(url) ;
document.getElementsByTagName("head")[0].appendChild(script);
}
return f;
}
function loadScripts(urls) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = urls.pop();
script.onload = loadScript(urls) ;
document.getElementsByTagName("head")[0];.appendChild(script);
}
loadScripts(["aaa.js","bbb.js","ccc.js"]);
Thank you!
-sorry for confusing you.. I added a function that actually calls loadScript(). (I checked this works.. )