Skip to content

Instantly share code, notes, and snippets.

@surma
Created May 6, 2017 17:17
Show Gist options
  • Save surma/09f3aada1417b36823433c0977ffc161 to your computer and use it in GitHub Desktop.
Save surma/09f3aada1417b36823433c0977ffc161 to your computer and use it in GitHub Desktop.
Polyfill for dynamic module loading
_registry = {};
importPolyfill = path => {
if(!(path in _registry)) {
const entry = _registry[path] = {};
entry.promise = new Promise(resolve => entry.resolve = resolve);
document.head.appendChild(Object.assign(
document.createElement('script'),
{
type: 'module',
innerText: `import * as X from '${path}'; _registry['${path}'].resolve(X);`,
}
));
}
return _registry[path].promise;
}
r={},importPolyfill=(a)=>{if(!(a in r)){const b=r[a]={};b.p=new Promise((c)=>b.r=c),document.head.appendChild(Object.assign(document.createElement('script'),{type:'module',innerText:`import * as X from '${a}'; r['${a}'].r(X);`}))}return r[a].p};
@samthor
Copy link

samthor commented Jun 16, 2017

I added onerror support for the script tag, and escaping, here: https://gist.github.com/samthor/3ff82bd5b11314fec2e1826d4a96ce7c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment