✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Run JavaScript After DOM is Loaded Without jQuery

Aug 4, 2020 2 min read

We’ve all used jQuery’s .ready() function:

$("document").ready(function () {});

This has been the simplest, cross-browser compatible way to ensure that our page is loaded and ready to be accessed and modified.

What if it’s 2020, and we don’t use jQuery anymore?

How can we do this is plain JavaScript?

Suppose we have this function that we want to run once the DOM is accessible to us:

const onReady = () => {
  console.log("DOM is available!");
}

The Easiest Way

The fastest way to go about this in JavaScript is to run a self-executing function in a script appended at the end of the <body> element.

<!doctype html>
<html>
  <head></head>
  <body>
    <!-- Some HTML -->
    <script>
      (function() {
        onReady();
      })();
    </script>
  </body>
</html>

Because the script runs at the end of the <body> element, it will only run after all the DOM is processed and loaded onto the page.

This is compatible on all browsers.

The Alternative Way

Suppose we don’t want our script to lie at the end of the <body> element. In this case, we can write this areWeReady() function to check if the DOM is already available.

If so, we’ll call the input function on the next available cycle.

If not, we’ll add an event listener that will wait for the DOM to be loaded.

function areWeReady(fn) {
  if (document.readyState === "complete" || document.readyState === "interactive") {
    setTimeout(fn, 1);
  } else {
    document.addEventListener("DOMContentLoaded", fn);
  }
}

We can invoke this function and then pass in onReady() from above.

areWeReady(onReady());

The great thing here is that this will work on modern browsers (Chrome, Firefox, Safari, and anything after IE9).


More JavaScript Articles