Last post we discussed different ways to load javascripts into the header and now I discovered when some function is dependent on some script being loaded, the earlier solution did not cover that.

Here is the example of the masterscript:

var scriptMap =[... whatever scripts ...];// list of to be loaded script in an array
function include(file){
var script = document.createElement(’script’);
script.src = file;
document.head.appendChild(script);
}
/*basic include any js files here */
for(var i=0;i<scriptMap.length;i++) include(scriptMap[i]);
//or
include(’script1.js’);
include(’script2.js’);

/* this helps */
function loadScript( url, callback ) {
var script = document.createElement( “script” )
script.type = “text/javascript”;
if(script.readyState) { //IE
script.onreadystatechange = function() {
if ( script.readyState === “loaded” || script.readyState === “complete” ) {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName( “head” )[0].appendChild( script );
}
// call the function…
loadScript(script3.js’, function() {
alert(’script3 ready now!’);
});
loadScript(’script4.js’, function() {
//alert(’script4 ready now!’);
load_other_script();
});
loadScript(‘/script5.js’, function() {
//alert(’script5 ready now!’);
script6();
});

function load_other_script(){
var imported = document.createElement(’script’);
imported = document.createElement(’script’);
imported.src = ‘/script7.js’;
document.head.appendChild(imported);
include(‘/script8.js’);
}

In addition to make one script loaded one after another, this will make sure one script is loaded and ready for another script to be load as the later script is dependent on the first script to be loaded .