Skip to content

Instantly share code, notes, and snippets.

View samthor's full-sized avatar

Sam Thorogood samthor

View GitHub Profile
@samthor
samthor / importPolyfill.js
Last active February 6, 2024 02:18 — forked from surma/importPolyfill.js
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);`,
});