44

Possible Duplicate:
$(document).ready equivalent without jQuery

I know you can use the window.onload event to make functions run, but is there a way for a script to query if the document is ready or not?

Something like

function update()
{
    if( !document.ready() )  // don't do unless document loaded
        return ;
}
window.setInterval( 'update();', 100 ) ;

Cannot change the <body> element, and no jQuery/other libraries.

4
  • @justkt The OP is not searching for a ready equivalent, but for a method to query whether or not the document has become ready. Apr 18, 2011 at 18:16
  • @Šime - ready does check whether the document has become ready, then fires events if any are bound to it.
    – justkt
    Apr 18, 2011 at 18:18
  • 1
    @justkt Binding a handler to the "ready" event is one thing and querying if the document is ready is another thing. The OP is doing the latter, and that other question the former. Those are two different things. Apr 18, 2011 at 18:33
  • DOMContentLoaded event?
    – advncd
    May 4, 2015 at 3:33

3 Answers 3

82

Here you go:

var tid = setInterval( function () {
    if ( document.readyState !== 'complete' ) return;
    clearInterval( tid );       
    // do your work
}, 100 );

Read about the document.readyState property here. I am not sure if all current browsers implement it.

4
  • 7
    Grrrrreat answer!! Tested Chrome, IE6,7,and 9, Firefox 4, Opera 11 it works.
    – bobobobo
    Apr 18, 2011 at 21:23
  • Yes great answer indeed. Works in all major browsers. Sorry, the post is late, but still want to ask, Why is it needed to do setInterval for 100ms? Won't it still check without setInterval object.
    – Sanjay
    Mar 3, 2015 at 5:48
  • 1
    @Yegya setInterval ensures that we keep checking repeatedly, every 100ms, until the document becomes 'complete'. Mar 3, 2015 at 5:51
  • Oh yes, sorry, I misthought for a second for setInterval to setTimeout. My bad... Thanx for calrifying though.
    – Sanjay
    Mar 3, 2015 at 6:23
2

Checkout https://github.com/jakobmattsson/onDomReady

It's more complicated than a few lines! - If you want multiple browser compliance.

-6

This code will work in all browsers

if(window.attachEvent()){

    window.attachEvent("onload",load);

 }else{

    window.addEventListener("load",load,true);

 }

 function load(){
    //Code to execute when the document is loaded.
 }
1
  • 2
    That, again, is the load, not the ready event. These are different. Sep 28, 2012 at 8:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.