forked from nqdeng/ocean
/
loader.js
64 lines (54 loc) · 1.3 KB
/
loader.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
63
64
// Asynchronous JS file loader.
var loader = (function () {
var pending = {},
head = document.getElementsByTagName('head')[0],
base = head.getElementsByTagName('base')[0],
/**
* Script element onload handler.
* @param el {Object}
* @callback {Function}
*/
onload = function (el, callback) {
if ('onload' in el) { // For standard browsers.
el.onload = function () {
callback();
};
} else if ('onreadystatechange' in el) { // For legacy IE.
el.onreadystatechange = function () {
var state = this.readyState;
if (state === 'loaded' || state === 'complete') {
el.onreadystatechange = null;
callback();
}
};
}
},
exports = {
/**
* Load a JS file.
* @param uri {string}
*/
load: function (uri) {
var el;
if (!pending[uri]) {
// Avoid duplicated loading at the same time.
pending[uri] = true;
el = document.createElement('script');
el.src = uri;
el.charset = config.charset;
el.async = 'async';
onload(el, function () {
// Clean useless DOM element.
head.removeChild(el);
delete pending[uri];
});
if (base) { // Avoid a known bug in IE6.
head.insertBefore(el, base);
} else {
head.appendChild(el);
}
}
}
};
return exports;
}());