41

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.

Community
  • 1
  • 1
bobobobo
  • 57,855
  • 58
  • 238
  • 337
  • @justkt The OP is not searching for a ready equivalent, but for a method to query whether or not the document has become ready. – Šime Vidas Apr 18 '11 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 '11 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. – Šime Vidas Apr 18 '11 at 18:33
  • DOMContentLoaded event? – advncd May 04 '15 at 03:33

3 Answers3

78

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.

Mark Amery
  • 110,735
  • 57
  • 354
  • 402
Šime Vidas
  • 163,768
  • 59
  • 261
  • 366
  • 7
    __Grrrrreat answer!!__ Tested Chrome, IE6,7,and 9, Firefox 4, Opera 11 it works. – bobobobo Apr 18 '11 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 03 '15 at 05:48
  • 1
    @Yegya `setInterval` ensures that we keep checking *repeatedly*, every 100ms, until the document becomes `'complete'`. – Šime Vidas Mar 03 '15 at 05:51
  • Oh yes, sorry, I misthought for a second for setInterval to setTimeout. My bad... Thanx for calrifying though. – Sanjay Mar 03 '15 at 06:23
2

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

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

James Kyburz
  • 11,891
  • 1
  • 29
  • 33
-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.
 }