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. Commented 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. Commented 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. Commented Apr 18, 2011 at 18:33
  • DOMContentLoaded event? Commented May 4, 2015 at 3:33

3 Answers 3

83

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Grrrrreat answer!! Tested Chrome, IE6,7,and 9, Firefox 4, Opera 11 it works.
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.
@Yegya setInterval ensures that we keep checking repeatedly, every 100ms, until the document becomes 'complete'.
Oh yes, sorry, I misthought for a second for setInterval to setTimeout. My bad... Thanx for calrifying though.
2

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

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

Comments

-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 Comment

That, again, is the load, not the ready event. These are different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.