Last active
August 21, 2023 09:02
-
-
Save domenic/fd84ee5f4e2dc0278ab1 to your computer and use it in GitHub Desktop.
Import module function (assuming <script type="module"> is implemented)
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
// 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) | |
); | |
} | |
} |
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
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); | |
}); | |
} |
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
// 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