JS - Run function when elements load

Outline

This post displays a JS snippet I wrote recently to watch for specific elements to be loaded into the DOM and then run a function (callBack) on them once they have loaded. This can be helpful when you are unable to directly edit the AJAX on-load function or simply want to separate your code from the AJAX code. It can also be used to run on page load, but that may be better suited to using the DOMContentLoaded event.

How to use it

  1. Add the below code into your JS file near the top so you can reference it later.
  2. Figure out a CSS selector for the elements you want to watch for. Make sure is specific enough to not grab unwanted elements. Ex. .my-ajax-div
  3. Decide how often you want to check whether the elements have loaded or not. You don't want to do it too often or it may affect performance. 100-500 ms is often sufficient to catch the elements fast and efficiently.
  4. Decide whether or not you want to keep checking after the first set of elements is loaded. If you do, then after the callback is run on a group of elements, a loaded-already class is added to make sure we don't run the callback again on them.
  5. Write your callback function. Note, this takes in an array of the loaded elements for you to manipulate.
  6. Lastly, run the callback: checkElementLoaded(selector, callBack, delay_ms, keepChecking=false)

The code

/**
 * A function that will run at a set interval (in ms) and check to 
 * see if an element or several elements have loaded on the page.
 * 
 * Optionally, you can enable 'keepChecking' to continue checking 
 * for new elements after the first ones have loaded. This will
 * continuously run in the background at your set interval. Loaded 
 * elements have a 'loaded-already' class added to them to ensure
 * we do not run the callback multiple times on the same element.
 * 
 * EXAMPLE:
 *  function do_something(loadedElements) {...}
 *  checkElementLoaded('.my-ajax-div', do_something, 500, true);
 * 
 * BY: Isaac Lehman - IsaacsTechBlog.com
 * 
 * @param selector CSS Selector for the element(s) you are checking for.
 * @param callBack The function to run after the element(s) have loaded on the page. Param is an array of the elements loaded.
 * @param delay_ms How many milliseconds between checks.
 * @param keepChecking (T/F) Should we keep checking for new elements after the current element has loaded
 */
function checkElementLoaded(selector, callBack, delay_ms, keepChecking=false) {
  if(keepChecking) {
    // Make sure we don't select elements
    // we have already run the callback
    // on.
    selector += ":not(.loaded-already)";
  }

  var interval = setInterval(function () {
    let curElementsCheck = document.querySelectorAll(selector);
    if (curElementsCheck.length) { // Was the element loaded?
      if(!keepChecking) {
        // Stop looking
        clearInterval(interval); 
      } 

      console.log("Elements loaded.");
      callBack(curElementsCheck);

      if(keepChecking) {
        curElementsCheck.forEach(ele => {
          // Mark the elment as already loaded
          // so we don't run the callback on 
          // it again.
          ele.classList.add('loaded-already');
        });
      }
    }
  }, delay_ms);
}

Comments

Login to Add comments.