This repository has been archived by the owner on Nov 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncloader.js
62 lines (56 loc) · 1.88 KB
/
asyncloader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* Copyright (C) 2013 Sam-Mauris Yong. All rights reserved.
* This file is part of the asyncloader.js project, which is released under New BSD 3-Clause license.
* See file LICENSE or go to http://opensource.org/licenses/BSD-3-Clause for full license details.
*/
var AsyncLoader = (function(loader, d){
var s = 'script',
fjs = d.getElementsByTagName(s)[0],
waiting = [];
var removeInArray = function(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax = arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
};
var processWaiting = function(id){
for (var idx in waiting) {
var item = waiting[idx];
item.depends = removeInArray(item.depends, id);
if (item.depends.length == 0) {
if( typeof item.url === 'function') {
item.url();
} else {
window.setTimeout(function(){
loader.add(item.url, item.id, item.load);
}, 0);
}
}
}
};
loader.add = function(u, id, load) {
if (d.getElementById(id)) {return;}
var js = d.createElement(s);
js.src = u;
id && (js.id = id);
js.onload = function(){
load && load.call(this);
processWaiting(id);
};
fjs.parentNode.insertBefore(js, fjs);
};
loader.depends = function(depends, url, id, load){
depends = typeof depends == 'string' ? [depends] : depends;
waiting.push({
depends: depends || [],
url: url,
id: id,
load: load
});
};
return loader;
})(AsyncLoader || {}, document);