javascriptes6-modulesscript-tagdomcontentloaded

The module / DOMContentLoaded event conundrum


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...


Solution

  • 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.