Skip to content

Instantly share code, notes, and snippets.

@ryaninvents
Last active March 3, 2021 17:06
Show Gist options
  • Save ryaninvents/239030903a3814d4111e8513e886a421 to your computer and use it in GitHub Desktop.
Save ryaninvents/239030903a3814d4111e8513e886a421 to your computer and use it in GitHub Desktop.
Loading ESM from regular JS
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