I want to import ES6 modules into my code. So I had to make my own script an ES6 module because else it is not possible. My code looks like this:
index.html:
<script type="module" src="script.js"></script>
<script>console.log("html is executed");</script>
<div id="display">1 is selected</div>
<select onchange="changed()"><option selected>1</option><option>2</option></select>
script.js:
window.changed = function()
{
document.getElementById("display").textContent = event.target.value;
}
console.log("script.js is executed");
The console output looks like this. Please look exactly at the output. The HTML is executed before script.js.
html is executed
script.js is executed
The problem is that it's possible the user changes the drop down and an error happens because changed()
isn't yet defined. That is when the page loads slowly. I verified this and it really happens.
I could assign the .onchange
programmatically in the script. But then it is possible that the user changes the value and nothing happens because .onchange
is not assigned yet (when the page loads slowly). Also I'd have to check in script.js
if the user has changed the value while .onchange
wasn't assigned yet.
It's a little sad because without type="module"
everything works fine. But now I have to extra code and things get more complex.
Isn't it possible to execute an ES6 module before the subsequent HTML code is executed? Just like a normal JS script?
Note on possible duplicates
This is not a duplicate of Execution order of ES6 imports, in HTML and in code. Also it's not a duplicate of What is the defined execution order of ES6 imports?. (Both questions are about having multiple modules).
Update
Unfortunately setting async="false" defer="false"
on the script tag didn't help.
Also in the comments was said that the module is loaded before DOMContentLoaded is fired. But how does that prevent the user from changing the drop down before the page has loaded (firing an onchange event)?