dynamicLoadScript.js
1.51 KB
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
let callbacks = [];
const dynamicLoadScript = (src, callback) => {
const existingScript = document.getElementById(src);
const cb = callback || function() {};
if (!existingScript) {
const script = document.createElement('script');
script.src = src; // src url for the third-party library being loaded.
script.id = src;
document.body.appendChild(script);
callbacks.push(cb);
const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd;
onEnd(script);
} else if (existingScript && cb) {
cb(null, existingScript);
}
function stdOnEnd(script) {
script.onload = function() {
// this.onload = null here is necessary
// because even IE9 works not like others
this.onerror = this.onload = null;
for (const cb of callbacks) {
cb(null, script);
}
callbacks = null;
};
script.onerror = function() {
this.onerror = this.onload = null;
cb(new Error('Failed to load ' + src), script);
};
}
function ieOnEnd(script) {
script.onreadystatechange = function() {
if (this.readyState !== 'complete' && this.readyState !== 'loaded') { return; }
this.onreadystatechange = null;
for (const cb of callbacks) {
cb(null, script); // there is no way to catch loading errors in IE8
}
callbacks = null;
};
}
};
export default dynamicLoadScript;