Skip to content

Instantly share code, notes, and snippets.

@samthor
samthor / importPolyfill.js
Last active Aug 11, 2022 — forked from surma/importPolyfill.js
Polyfill for dynamic module loading that supports onerror
View importPolyfill.js
// 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);`,
});