Last active
March 3, 2021 17:06
-
-
Save ryaninvents/239030903a3814d4111e8513e886a421 to your computer and use it in GitHub Desktop.
Loading ESM from regular JS
This file contains hidden or 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
function addModule(src) { | |
return new Promise((ok, fail) => { | |
const script = document.createElement('script'); | |
const id = `module-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`; | |
const body = ` | |
import * as myModule from ${JSON.stringify(src)}; | |
document.getElementById(${JSON.stringify(id)}).dispatchEvent(new CustomEvent('moduleloaded', {detail: myModule})); | |
`; | |
script.setAttribute('id', id); | |
script.addEventListener('moduleloaded', (event) => ok(event.detail)); | |
script.onerror = (error) => fail(error); | |
script.setAttribute('type', 'module'); | |
script.innerHTML = body; | |
document.head.appendChild(script); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment