-
-
Save asvny/0ff1b70aebfc247fe560dc93a96a19e5 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment