-
-
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 |
somewhat similar for nodejs?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why is this not a full replacement for
import()
?Because
import()
uses the current path of the file you're callingimport()
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.