How to detect if document has loaded using Javascript or Jquery

A page can’t be manipulated safely until the document is “ready.” You might come across various scenarios where you need to call some function or perform some tasks only after the document has loaded completely. So how do you detect if the document has loaded completely?

Detect if Document has loaded properly using JS

if (document.readyState === "complete") {

This can also be done inside the interval

var interval = setInterval(function() {
    if(document.readyState === 'complete') {
}, 100);

The document.readyState can be one of the following:

  • loading -The document is still loading.
  • interactive -The document has finished the loading but still the other sub-resources like JS, Images, StlyeSheets etc are still loading. The state indicates that the DOMContentLoaded event has been fired.
  • complete -The document and all sub-resources have finished loading. The state indicates that the load event has been fired.

Example for Different State of Document Readiness

switch (document.readyState) {
  case "loading":
    // The document is still loading.
  case "interactive":
    // The document has finished loading. We can now access the DOM elements.
    var span = document.createElement("span");
    span.textContent = "A <span> element.";
  case "complete":
    // The page is fully loaded.
    console.log("Page is loaded completely");

Jquery to check if DOM has loaded
Even the Jquery internally uses the above Javascript method to detect if document has loaded. However if you are using Jquery to check if the document has loaded then below is the sample snippet which you can use to achieve the same functionality.

Check if Document has loaded properly using Jquery

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );

Jquery to check if entire document has loaded
If you need to perform an action after the complete pages are loaded including all the resources then best approach is to use $( window ).load(function() { … }) which will run once the entire page (images or iframes), not just the DOM, is ready.

Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like