I have this simple function which loads scripts into the current DOM:
function loadscripts ( async ) { if( async === undefined ) { async = false; } var scripts = []; var _scripts = ['jquery.min.js', 'bootstrap.min.js', 'plugins.js', 'main.js']; for(var s in _scripts) { scripts[s] = document.createElement('script'); scripts[s].type = 'text/javascript'; scripts[s].src = _scripts[s]; scripts[s].async = async; document.getElementsByTagName('head').appendChild( scripts[s] ); } }
They are loaded fine and without no errors. I know there are event handlers when loading scripts programmatically:
- onreadystatechange, and
- onload, etc
Now I would like to wish to do the following:
- Load first script from the array, and when the event handlers are COMPLETE load the next one, and so on (recursively).
Sorry, I have not provided the onreadystatechange
and onload
events in my function.
Advertisement
Answer
I would do this that way :
LoadScripts(); function LoadScripts(async) { if( async === undefined ) { async = false; } var scripts = []; var _scripts = ['jquery.min.js', 'bootstrap.min.js', 'plugins.js', 'main.js']; if(async){ LoadScriptsAsync(_scripts, scripts) }else{ LoadScriptsSync(_scripts,scripts) } } // what you are looking for : function LoadScriptsSync (_scripts, scripts) { var x = 0; var loopArray = function(_scripts, scripts) { // call itself loadScript(_scripts[x], scripts[x], function(){ // set x to next item x++; // any more items in array? if(x < _scripts.length) { loopArray(_scripts, scripts); } }); } loopArray(_scripts, scripts); } // async load as in your code function LoadScriptsAsync (_scripts, scripts){ for(var i = 0;i < _scripts.length;i++) { loadScript(_scripts[i], scripts[i], function(){}); } } // load script function with callback to handle synchronicity function loadScript( src, script, callback ){ script = document.createElement('script'); script.onerror = function() { // handling error when loading script alert('Error to handle') } script.onload = function(){ console.log(src + ' loaded ') callback(); } script.src = src; document.getElementsByTagName('head')[0].appendChild(script); }