Martin Boynton
Martin Boynton

Reputation: 125

How can I check if the DOM is ready without a listener?

If I have a script that is loaded dynamically, I want it to wait until the DOM is ready before executing code. However, if the script loads too slowly, the DOM will already be ready and therefore the DOM-Ready function will not run.

No frameworks, please, I'm relying on pure JavaScript.

Thanks in advance!

Upvotes: 0

Views: 1068

Answers (5)

RobG
RobG

Reputation: 147383

Very simple - put your script immediately before the closing body tag (if you have one). It doesn't guarantee that the DOM is ready, but it's more reliable that DOM ready listeners and runs earlier than load listeners.

Upvotes: 1

arahaya
arahaya

Reputation: 1020

snippet that checks the document.readyState

http://www.dustindiaz.com/smallest-domready-ever

Upvotes: 0

James Black
James Black

Reputation: 41858

Part way down on this page: http://dean.edwards.name/weblog/2006/06/again/ you will find this code, which is what I use to do what you are asking about:

I leave the comment with the code as I didn't write it:

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 47988

Without a listener there's no 100% reliable way to ensure that the entire DOM is loaded. You can do something like this:

var myChecker = setInterval(function () {
  var checkElem = document.getElementById('myRefElement');

  if (checkElem != null) {
    clearInterval(myChecker);
    myFunction();
  }
}, 100);

That'll wait until some target element you care about exists.

Upvotes: 1

Moin Zaman
Moin Zaman

Reputation: 25445

Here are a couple of pure javascript domready events:

http://snipplr.com/view/6029/domreadyjs/

http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/

Upvotes: 0

Related Questions