My website has event listeners for various actions. I currently add these event listeners to my elements once the whole DOM has loaded, like this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("someid").addEventListener("click", somefunction(); });
})
I've gotten feedback from some users with poor internet connexion that they have to wait sometimes up to a full minute for the whole page to load before the website to work properly..
Is there a way to add an event listener to an element the instant it loads on the page instead of waiting for the whole DOM to load? I'd rather not go back to using onclick="" within the HTML like in the olden days.
By choice, I only use vanilla JavaScript.
Unfortunately there is not a lot you can do apart from just optimizing and speeding up your site.
Js event listeners only become active once entire DOM has been loaded and parsed.
You can include the script tag (loading js) within the head section of your html file + use defer (or type="module") attribute to ensure that the js downloads concurrently to html and only executes after HTML fully parsed.
<script src="your_script.js" defer></script>Some other optimizations include: lazy loading and optimizating files