Skip to content

Instantly share code, notes, and snippets.

@colxi
Last active May 25, 2018 21:36
Show Gist options
  • Save colxi/a81f7263bad42412b7d1c365110570cd to your computer and use it in GitHub Desktop.
Save colxi/a81f7263bad42412b7d1c365110570cd to your computer and use it in GitHub Desktop.
Dynamic import function for ES modules polyfill
// Addapted from :
// https://github.com/tc39/proposal-dynamic-import
function importModule(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
const loaderId = "__tempModuleLoadingVariable" + Math.random().toString(32).substring(2);
window[loaderId] = function( m ){
resolve( m );
delete window[loaderId];
script.remove();
};
script.onerror = () => {
reject(new Error("Failed to load module script with URL " + url));
delete window[loaderId];
script.remove();
};
script.type = "module";
script.textContent = `import * as m from "${url}"; window.${loaderId}( m.default )`;
document.documentElement.appendChild(script);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment