Last active
May 25, 2018 21:36
-
-
Save colxi/a81f7263bad42412b7d1c365110570cd to your computer and use it in GitHub Desktop.
Dynamic import function for ES modules polyfill
This file contains 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
// 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