Skip to content

Instantly share code, notes, and snippets.

@domenic domenic/0-usage.js
Last active Mar 19, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.