I have this simple function which loads scripts into the current DOM:
JavaScript
x
18
18
1
function loadscripts ( async ) {
2
if( async === undefined ) {
3
async = false;
4
}
5
6
var scripts = [];
7
var _scripts = ['jquery.min.js', 'bootstrap.min.js', 'plugins.js', 'main.js'];
8
9
for(var s in _scripts) {
10
scripts[s] = document.createElement('script');
11
scripts[s].type = 'text/javascript';
12
scripts[s].src = _scripts[s];
13
scripts[s].async = async;
14
15
document.getElementsByTagName('head').appendChild( scripts[s] );
16
}
17
}
18
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 :
JavaScript
1
58
58
1
LoadScripts();
2
3
function LoadScripts(async)
4
{
5
if( async === undefined ) {
6
async = false;
7
}
8
var scripts = [];
9
var _scripts = ['jquery.min.js', 'bootstrap.min.js', 'plugins.js', 'main.js'];
10
11
if(async){
12
LoadScriptsAsync(_scripts, scripts)
13
}else{
14
LoadScriptsSync(_scripts,scripts)
15
}
16
}
17
18
// what you are looking for :
19
function LoadScriptsSync (_scripts, scripts) {
20
21
var x = 0;
22
var loopArray = function(_scripts, scripts) {
23
// call itself
24
loadScript(_scripts[x], scripts[x], function(){
25
// set x to next item
26
x++;
27
// any more items in array?
28
if(x < _scripts.length) {
29
loopArray(_scripts, scripts);
30
}
31
});
32
}
33
loopArray(_scripts, scripts);
34
}
35
36
// async load as in your code
37
function LoadScriptsAsync (_scripts, scripts){
38
for(var i = 0;i < _scripts.length;i++) {
39
loadScript(_scripts[i], scripts[i], function(){});
40
}
41
}
42
43
// load script function with callback to handle synchronicity
44
function loadScript( src, script, callback ){
45
46
script = document.createElement('script');
47
script.onerror = function() {
48
// handling error when loading script
49
alert('Error to handle')
50
}
51
script.onload = function(){
52
console.log(src + ' loaded ')
53
callback();
54
}
55
script.src = src;
56
document.getElementsByTagName('head')[0].appendChild(script);
57
}
58