Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if DOM is ready without a framework?

The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here's the catch:

  • Without using a framework like jQuery etc;
  • Without knowing if your script has been loaded via a statically placed <script> tag or via some other Javascript much later after the DOM has already loaded.

Can this be done more or less reliably and with cross-browser compatibility?

Added: Let me clarify: I'm writing a standalone .JS file which can be included in arbitrary webpages. I want to execute code AFTER the DOM has been loaded. But I don't know HOW my script will be included. It could be by placing a <script> tag (in which case the traditional onload or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire).

like image 594
Vilx- Avatar asked Nov 11 '11 22:11

Vilx-


People also ask

How do I know if my DOM is ready?

It could be by placing a <script> tag (in which case the traditional onload or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire). The document.

How do I know if my document is ready?

To check if the document is ready and run some code, you can add an event handler to the DOMContentLoaded event of the document object. The DOMContentLoaded event is fired when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Which event is used to check whether DOM is loaded or not?

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A different event, load , should be used only to detect a fully-loaded page.

How will you make sure that DOM is ready using jQuery?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.


2 Answers

The document.readyState property can be used to check if the document is ready. From MDN:

Values

The readyState of a document can be one of following:

  • loading – The document is still loading.
  • interactive – The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
  • complete – The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.

Code example:

if(document.readyState === "complete") {     // Fully loaded! } else if(document.readyState === "interactive") {     // DOM ready! Images, frames, and other subresources are still downloading. } else {     // Loading still in progress.     // To wait for it to complete, add "DOMContentLoaded" or "load" listeners.      window.addEventListener("DOMContentLoaded", () => {         // DOM ready! Images, frames, and other subresources are still downloading.     });      window.addEventListener("load", () => {         // Fully loaded!     }); } 
like image 166
Digital Plane Avatar answered Sep 27 '22 22:09

Digital Plane


Firefox, Opera and Webkit-based browsers have a document-level event DOMContentLoaded that you can listen for with document.addEventListener("DOMContentLoaded", fn, false).

It is more complicated in IE. What jQuery does in IE is watch onreadystatechange on the document object for a particular readystate with a backup of the document.onload event. document.onload fires later than the DOM is ready (only when all images have finished loading) so it's only used as a backstop in case the earlier events don't work for some reason.

If you spend some time Googling, you will find code to do this. I figure the most vetted code to do this is in the large frameworks like jQuery and YUI so, even if I'm not using that framework, I look in their source code for techniques.

Here's the main part of jQuery 1.6.2 source for document.ready():

bindReady: function() {     if ( readyList ) {         return;     }      readyList = jQuery._Deferred();      // Catch cases where $(document).ready() is called after the     // browser event has already occurred.     if ( document.readyState === "complete" ) {         // Handle it asynchronously to allow scripts the opportunity to delay ready         return setTimeout( jQuery.ready, 1 );     }      // Mozilla, Opera and webkit nightlies currently support this event     if ( document.addEventListener ) {         // Use the handy event callback         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );          // A fallback to window.onload, that will always work         window.addEventListener( "load", jQuery.ready, false );      // If IE event model is used     } else if ( document.attachEvent ) {         // ensure firing before onload,         // maybe late but safe also for iframes         document.attachEvent( "onreadystatechange", DOMContentLoaded );          // A fallback to window.onload, that will always work         window.attachEvent( "onload", jQuery.ready );          // If IE and not a frame         // continually check to see if the document is ready         var toplevel = false;          try {             toplevel = window.frameElement == null;         } catch(e) {}          if ( document.documentElement.doScroll && toplevel ) {             doScrollCheck();         }     } }, 
like image 40
jfriend00 Avatar answered Sep 27 '22 21:09

jfriend00