skip to Main Content

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


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

    Login or Signup to reply.
  2. 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):

    <button id="someid">Click me</button>
    <script>
        document.getElementById("someid").addEventListener("click", somefunction(); })
    </script>
    

    That way the event listener should be set immediately after the button is rendered in the DOM.

    Login or Signup to reply.
  3. 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.

    document.addEventListener('click', function(e) {
      if (e.target.id == 'someid');
        somefunction.call(e.target, e);  
      }
    });
    

    Or if you want to do something much less boring you can try dom mutation observer

    function addHandler(records, observer) {
      for (const record of records) {
        for (const addedNode of record.addedNodes) {
          if (addedNode.id == 'someid'){
            addedNode.addEventListener("click", somefunction);
            //when all your event listeners are attached stop observing
            observer.disconnect();
          }
        }
      }
    }
    
    const observerOptions = {
      childList: true,
      subtree: true,
    };
    
    const observer = new MutationObserver(addHandler);
    observer.observe(document.documentElement, observerOptions);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search