Categories
JavaScript Answers

How to Check if the DOM is Ready without Any JavaScript Framework or Library?

Spread the love

Sometimes, we want to check if the DOM is ready without any JavaScript framework or library.

In this article, we’ll look at how to check if the DOM is ready without any JavaScript framework or library.

Check if the DOM is Ready without Any JavaScript Framework or Library

To check if the DOM is ready without any JavaScript framework or library, we can listen to the DOMContentLoaded or the load event.

Inside the event handlers for each event, we can check the value of the document.readyState property to determine if the DOM is ready or not.

For instance, we can write:

window.addEventListener("DOMContentLoaded", () => {
  if (document.readyState === "complete") {
    console.log('loaded')
  } else if (document.readyState === "interactive") {
    // DOM ready! Images, frames, and other subresources are still downloading.
  }
});

window.addEventListener("load", () => {
  if (document.readyState === "complete") {
    console.log('loaded')
  } else if (document.readyState === "interactive") {
    // DOM ready! Images, frames, and other subresources are still downloading.
  }
});

We listen for the DOMContentLoaded and load events by calling window.addEventListener .

Then in each event handler, we check the document.readyState value.

If the value is 'complete' , then we know the DOM is fully loaded.

If it’s 'interactive' , then the DOM is ready, but images, frames, and other resources are still loading.

Conclusion

To check if the DOM is ready without any JavaScript framework or library, we can listen to the DOMContentLoaded or the load event.

Inside the event handlers for each event, we can check the value of the document.readyState property to determine if the DOM is ready or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *