Skip to content

Instantly share code, notes, and snippets.

@asvny
Forked from tbranyen/importScript.js
Created May 29, 2017 04:22
Show Gist options
  • Save asvny/0ff1b70aebfc247fe560dc93a96a19e5 to your computer and use it in GitHub Desktop.
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)
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