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.
3
Answers
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
The easiest, but somewhat ugly way to do this is as follows (I’m using a button as an example, but works with any tag):
That way the event listener should be set immediately after the button is rendered in the DOM.
You can use event delegation, add a listener to the document so you don’t have to wait for everything to load and then check where the event came from.
Or if you want to do something much less boring you can try dom mutation observer