-
-
Save samthor/3ff82bd5b11314fec2e1826d4a96ce7c to your computer and use it in GitHub Desktop.
Polyfill for dynamic module loading that supports onerror
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage: | |
// importScript('./path/to/script.js').then((allExports) => { .... })); | |
function importScript(path) { | |
let entry = window.importScript.__db[path]; | |
if (entry === undefined) { | |
const escape = path.replace(`'`, `\\'`); | |
const script = Object.assign(document.createElement('script'), { | |
type: 'module', | |
textContent: `import * as x from '${escape}'; importScript.__db['${escape}'].resolve(x);`, | |
}); | |
entry = importScript.__db[path] = {}; | |
entry.promise = new Promise((resolve, reject) => { | |
entry.resolve = resolve; | |
script.onerror = reject; | |
}); | |
document.head.appendChild(script); | |
script.remove(); | |
} | |
return entry.promise; | |
} | |
importScript.__db = {}; | |
window['importScript'] = importScript; // needed if we ourselves are in a module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
somewhat similar for nodejs?