Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active August 21, 2023 09:02
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domenic/fd84ee5f4e2dc0278ab1 to your computer and use it in GitHub Desktop.
Save domenic/fd84ee5f4e2dc0278ab1 to your computer and use it in GitHub Desktop.
Import module function (assuming <script type="module"> is implemented)
// Dynamic module loading using runtime-composed strings, decisions, etc.
for (const m of ["cool", "awesome", "fun", "whee"]) {
if (Math.random() > 0.5) {
importModule(`/js/${m}.js`).then(
module => console.log("Module instance object for " + m, module),
e => console.error(e)
);
}
}
function importModule(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
const tempGlobal = "__tempModuleLoadingVariable" + Math.random().toString(32).substring(2);
script.type = "module";
script.textContent = `import * as m from "${url}"; window.${tempGlobal} = m;`;
script.onload = () => {
resolve(window[tempGlobal]);
delete window[tempGlobal];
script.remove();
};
script.onerror = () => {
reject(new Error("Failed to load module script with URL " + url));
delete window[tempGlobal];
script.remove();
};
document.documentElement.appendChild(script);
});
}
// Let's say we specced HTMLScriptElement.prototype.module to return the module instance object
function importModule(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.type = "module";
script.src = url;
script.onload = () => {
resolve(script.module);
script.remove();
};
script.onerror = () => {
reject(new Error("Failed to load module script with URL " + url));
script.remove();
};
document.documentElement.appendChild(script);
});
}
// Much less hacky... still have to insert into the document though.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment