-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_importer.js
More file actions
57 lines (51 loc) · 1.89 KB
/
dynamic_importer.js
File metadata and controls
57 lines (51 loc) · 1.89 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
48
49
50
51
52
53
54
55
56
57
/**
Created by Complynx on 22.03.2019,
http://complynx.net
<complynx@yandex.ru> Daniel Drizhuk
*/
import {generate_id} from "./mongo.js";
if(!window.dyn_import) {
/**
* ES6 `import()` backport.
* @param {string} url
* @returns {Promise<*>} imported module contents
*/
window.dyn_import = function (url) {
return new Promise((resolve, reject) => {
if(!url || url === "") throw new Error("No URL specified");
const script = document.createElement("script");
const tempGlobal = "__tempModuleLoadingVariable" + generate_id();
script.type = "module";
new Promise((resolve2, reject2) => {
window[tempGlobal] = {
resolve: resolve2,
reject: reject2
};
}).then((m) => {
resolve(m);
delete window[tempGlobal];
script.remove();
}, (m) => {
reject(m);
delete window[tempGlobal];
script.remove();
});
script.textContent = `
import * as m from "${url}";
import default as d from "${url}";
m['default'] = d;
clearTimeout(window.${tempGlobal}.timer);
window.${tempGlobal}.resolve(m);
`;
script.onerror = () => {
clearTimeout(window[tempGlobal].timer);
window[tempGlobal].reject(new Error("Failed to load module script with URL " + url));
};
window[tempGlobal].timer = setTimeout(script.onerror, window.dyn_import.timeout);
document.documentElement.appendChild(script);
});
};
window.dyn_import.timeout = 5000;
}
if(!window['import'] || typeof window['import'] !== "function") window['import'] = dyn_import;
else console.info("YAY, native import()!");