Last active
April 23, 2018 14:47
-
-
Save tbranyen/9496397c3f422ebadc382e7daffc1dc6 to your computer and use it in GitHub Desktop.
Native `import()` polyfill (Note: can't name it `import` due to reserved word limitations)
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
Object.defineProperty(window, Symbol.for('registry'), { | |
value: new Map(), | |
}); | |
window.importScript = src => { | |
const registry = window[Symbol.for('registry')]; | |
if (registry.has(src)) { | |
return registry.get(src).promise; | |
} | |
const record = { | |
src, | |
script: Object.assign(document.createElement('script'), { | |
type: 'module', | |
innerText: ` | |
import * as X from '${src}'; | |
window[Symbol.for('registry')].get('${src}').resolvers[0](X); | |
`, | |
onload: () => record.script.parentNode.removeChild(record.script), | |
onerror: err => { | |
registry.get(src).resolvers[1](err); | |
record.script.parentNode.removeChild(record.script); | |
}, | |
}), | |
}; | |
record.promise = new Promise((...resolvers) => record.resolvers = resolvers); | |
document.head.appendChild(record.script); | |
registry.set(src, record); | |
return record.promise; | |
}; | |
// importScript('https://diffhtml.org/es').then(diff => console.log(diff)); |
To handle multiple imports
(like AMD) you could write a function like importScripts
:
window.importScripts = srcs => Promise.all(srcs.map(src => importScript(src)));
importScripts([
'https://diffhtml.org/es',
'https://diffhtml.org/master/diffhtml-components',
]).then(([{ innerHTML }, { Component }]) => {
console.log(innerHTML, Component);
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mock dependencies with: