Skip to content

Instantly share code, notes, and snippets.

@samthor
Forked from surma/importPolyfill.js
Last active February 6, 2024 02:18
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samthor/3ff82bd5b11314fec2e1826d4a96ce7c to your computer and use it in GitHub Desktop.
Save samthor/3ff82bd5b11314fec2e1826d4a96ce7c to your computer and use it in GitHub Desktop.
Polyfill for dynamic module loading that supports onerror
// 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
@ganeshkbhat
Copy link

somewhat similar for nodejs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment