javascriptscript-tagdeferred-loading

Do modules prevent the need to use the DOMContentLoaded listener?


document.addEventListener('DOMContentLoaded', () => { 

});

I read that this event listener made sure, for regular scripts, that the JS wasn't going to reference nodes that hadn't been loaded yet. The content executes after DOMContentLoaded has been fired).

I've also read that a module is executed before DOMContentLoaded is fired (due to the defer attribute it has built in).

The modules I've used seem to not need the DOMContentLoaded listener. Can I confirm the DOMContentLoaded listener isn't needed by them to access nodes correctly?

Also, I can't think of how to test this so I'm asking here. If you know how I could, please do share!


Solution

  • I think this article should clear things for you, it has great pictures https://flaviocopes.com/javascript-async-defer/#the-position-matters

    When defer is present, it specifies that the script is executed when the page has finished parsing, therefore you can guarantee that the script gets access to the nodes without DOMContentLoaded