Files
svgedit/editor/external/dynamic-import-polyfill/importModule.js
Brett Zamir 5ad83b9b87 - Refactoring: Clean-up
- Fix: Race condition with svgicons and seticonsize
- Embedded editor: Use module form for now; drop unused inline attribute
- Embedded editor: Fix PNG export; work toward restoring PDF (add `getUIStrings` method to editor for assisting)
- canvg and importScript fixes
2018-05-25 22:43:01 +08:00

67 lines
1.8 KiB
JavaScript

// MIT License
// From: https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js
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"
}
// My own addition
export function importScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
const destructor = () => {
script.onerror = null;
script.onload = null;
script.remove();
script.src = "";
};
script.defer = "defer";
script.onerror = () => {
reject(new Error(`Failed to import: ${url}`));
destructor();
};
script.onload = () => {
resolve();
destructor();
};
script.src = url;
document.head.appendChild(script);
});
}
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;