/
js-loader.js
43 lines (37 loc) 路 1.27 KB
/
js-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
const cacheLoader = require('../cacheLoader');
module.exports = cacheLoader(function loadJSBundle(bundle) {
return new Promise(function (resolve, reject) {
// Don't insert the same script twice (e.g. if it was already in the HTML)
let existingScripts = document.getElementsByTagName('script');
let isCurrentBundle = function (script) {
return script.src === bundle;
};
if ([].concat(existingScripts).some(isCurrentBundle)) {
resolve();
return;
}
var preloadLink = document.createElement('link');
preloadLink.href = bundle;
preloadLink.rel = 'preload';
preloadLink.as = 'script';
document.head.appendChild(preloadLink);
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = bundle;
script.onerror = function (e) {
var error = new TypeError(
`Failed to fetch dynamically imported module: ${bundle}. Error: ${e.message}`,
);
script.onerror = script.onload = null;
script.remove();
reject(error);
};
script.onload = function () {
script.onerror = script.onload = null;
resolve();
};
document.getElementsByTagName('head')[0].appendChild(script);
});
});