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
@samthor
Copy link
Author

samthor commented Feb 28, 2019

Why is this not a full replacement for import()?

Because import() uses the current path of the file you're calling import() from as part of its argument (e.g., if the file is "/src/foo/lib.js" and I import "./stuff.js", this will resolve to "/src/foo/stuff.js").

You could use import.meta.url, which contains the current module script URL. But it's not supported in all browsers that also support modules, as it came much later than initial module support.

If you're using a build system though, it could trivially replace import() calls with a polyfill call that includes either the full resolved pathname, or in the case of actual dynamic imports, includes the path of the current file so userspace code can combine them into the final absolute path.

@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