forked from telepathic-elements/telepathic-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimportModule.js
39 lines (35 loc) · 1.16 KB
/
importModule.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
function toAbsoluteURL(url) {
const a = document.createElement("a");
a.setAttribute("href", url); // <a href="hoge.html">
return a.cloneNode(false).href; // -> "http://example.com/hoge.html"
}
export function importModule(url) {
return new Promise((resolve, reject) => {
const vector = "$importModule$" + Math.random().toString(32).slice(2);
const script = document.createElement("script");
const destructor = () => {
delete window[vector];
script.onerror = null;
script.onload = null;
script.remove();
URL.revokeObjectURL(script.src);
script.src = "";
};
script.defer = "defer";
script.type = "module";
script.onerror = () => {
reject(new Error(`Failed to import: ${url}`));
destructor();
};
script.onload = () => {
resolve(window[vector]);
destructor();
};
const absURL = toAbsoluteURL(url);
const loader = `import * as m from "${absURL}"; window.${vector} = m;`; // export Module
const blob = new Blob([loader], { type: "text/javascript" });
script.src = URL.createObjectURL(blob);
document.head.appendChild(script);
});
}
export default importModule;