I had an... interesting... use case at my company where I had to import functions from a file, but the script tag couldn't be a module.
The script tag creates a new script tag in the dom with type = module, which imports an object containing each function. For each of the functions we run window.myFunction = myFunction to allow them to be used from the dom.
HTML:
<script>
((path = "./importme.js", fileId = "importme") => {
if (document.getElementById(fileId)) return;
let tag = document.createElement("script");
tag.type = "module";
tag.id = fileId;
tag.innerHTML =
'import codeFromFile from "' +
path +
'"; Object.keys(codeFromFile).forEach(k => { window[k] = codeFromFile[k] });';
document.body.appendChild(tag);
})();
</script>
<button onclick="testFunction()">Click me</button>
./importme.js
function testFunction() {
alert("Test Function");
}
export default { testFunction };
Alternatively, if you just want to run what's in the imported file you could do this:
HTML:
<script>
((src = "/importme.js", fileId = "importme") => {
if (document.getElementById(fileId)) return;
let tag = document.createElement("script");
tag.id = fileId;
tag.src = src;
document.body.appendChild(tag);
})();
</script>
<button id="click">Click me</button>
./importme.js (wrap everything in the exported anonymous function)
window.onload = () => {
document.getElementById('click').onclick = e => {
alert('Element clicked!');
};
};
This is a bad way to do things, only for a worst-case scenario. This answer is food for thought, please don't do this... My company found a way to get around this in the end.
varto declare the variable so it will be accessible from another files.