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

This can also be done inside the interval

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

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

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.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.