The module / DOMContentLoaded event conundrum

54 views Asked by At

I used to have a js script which is imported in html as type text/javascript. Let's call it main.js I used a DOMContentLoaded event listener, so that as the page was loaded, we would run the script.

Now I need more functionality, and I had to create some modules to avoid putting all in a big file. To import the javascript functions into main.js, main.js must be imported in html as type module.

However, this makes the DOMContentLoaded event listener to never get triggered...

I searched, and in the MDN reference:

The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts (<script defer src="…"> and <script type="module">) have downloaded and executed.

This explains, I think, why it never gets triggered inside a type module.

Now, I'm looking for an alternative event... I've tried load but it doesn't seem to work...

2

There are 2 answers

0
An old man in the sea. On BEST ANSWER

After searching, the main problem was exactly what I wrote in my comments.

Module scripts require the use of the CORS protocol for cross-origin fetching.

If one is doing local testing, i.e. loading the HTML file locally (with a uri of the type file://), you'll run into CORS errors due to JavaScript module security requirements. We need to do the testing through a server.

In my case, I had to use my Python backend (FastAPI) to serve my webpage, and then it worked, even with the event listeners.

1
Bergi On

Scripts of type "module" are deferred automatically, which means they already execute after the DOM was completely loaded. You do not need to do anything yourself to that effect.

So just remove the DOMContentLoaded event registration and call the handler immediately.