Native `import()` polyfill (Note: can't name it `import` due to reserved word limitations)
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)); |
This comment has been minimized.
This comment has been minimized.
To handle multiple 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
This comment has been minimized.
tbranyen commentedMay 7, 2017
•
edited
Mock dependencies with: