Javascript domready?

JavascriptDom Events

Javascript Problem Overview


I know I can use different frameworks like prototype or jQuery to attach a function to the window.onload, but's not what I'm looking for.

I need something like .readyState so that I can do something like this:

if(document.isReady){
  var id = document.getElem ...
}

is there any other way than using what the frameworks do?

Javascript Solutions


Solution 1 - Javascript

Edit: As the year 2018 comes upon us, I think it's safe to listen for the DOMContentLoaded event.

function fireOnReady() { /* ... */ }
if (document.readyState === 'complete') {
    fireOnReady();
} else {
    document.addEventListener("DOMContentLoaded", fireOnReady);
}

> Please note, the event will only fire once when your page loads! If you have to support really old browsers, then check out the super lightweight script I put together below.



For historical reference only:



jQuery has an undocumented property called isReady which is used internally to determine whether the DOM ready event has fired:

if($.isReady) {
    // DOM is ready
} else {
    // DOM is not yet ready
}

I started at 1.5.2 went back as far as 1.3.2 and the property is there. While undocumented, I would say that you can rely on this property in future versions of jQuery. Edit: And a year later - v1.7.2, they still use $.isReady - still undocumented, so please use at your own risk. Be careful when upgrading.

Edit: v1.9, they still use $.isReady - still undocumented

Edit: v2.0, with all of it's "major" changes, still uses $.isReady - still undocumented

Edit: v3.x still uses $.isReady - still undocumented

Edit: As several people have pointed out, the above does not really answer the question. So I have just created a mini DOM ready snippet which was inspired by Dustin Diaz's even smaller DOM ready snippet. Dustin created a neat way to check the document readyState with something similar to this:

if( !/in/.test(document.readyState) ) {
    // document is ready
} else {
    // document is NOT ready
}

The reason this works is because the browser has 3 loading states: "loading", "interactive", and "complete" (older WebKit also used "loaded", but you don't have to worry about that any more). You will notice that both "loading" and "interactive" contain the text "in"... so if the string "in" is found inside of document.readyState, then we know we are not ready yet.

Solution 2 - Javascript

While I usually advocate avoiding using frameworks unless necessary, I'd say using one in this case is perfectly fine. Here's jQuery:

$(function () {
    // do stuff after DOM has loaded
});

Note that it is NOT the same as an window.onload event, since onload executes first after other resources have been loaded (images etc.) The code I used in my example will execute when the DOM has finished loading, i.e., when the full HTML structure is available (not necessarily when images, CSS, etc. is available.)

If you want a checkable variable, you can set one in the ready-function:

var documentIsReady = false;
$(function () { documentIsReady = true; });

Of course you can find even more light-weight libraries than jQuery if all you want to do is to check for DOM-ready. But use a library in cases where different browsers behave very differently (this is one such case.)

Using some code from the DOMAssistant library, making your own "DOM is ready" function shouldn't be too hard:

var domLoaded = function (callback) {
    /* Internet Explorer */
    /*@cc_on
    @if (@_win32 || @_win64)
        document.write('<script id="ieScriptLoad" defer src="//:"><\/script>');
        document.getElementById('ieScriptLoad').onreadystatechange = function() {
            if (this.readyState == 'complete') {
                callback();
            }
        };
    @end @*/
    /* Mozilla, Chrome, Opera */
    if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', callback, false);
    }
    /* Safari, iCab, Konqueror */
    if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
        var DOMLoadTimer = setInterval(function () {
            if (/loaded|complete/i.test(document.readyState)) {
                callback();
                clearInterval(DOMLoadTimer);
            }
        }, 10);
    }
    /* Other web browsers */
    window.onload = callback;
};

Not tested, but it should work. I simplified it from DOMAssistant, because DOMAssistant allows multiple callbacks and has checking to make sure you can't add the same function twice etc.

Solution 3 - Javascript

In the 5 years that have passed since this question was asked DOMContentLoaded has become a universally supported event, and you can just use that.

document.addEventListener('DOMContentLoaded', function() {
    //.. do stuff ..
}, false);

Solution 4 - Javascript

Check out this demo from microsoft. -> http://ie.microsoft.com/testdrive/HTML5/DOMContentLoaded/Default.html And here is the gist of the code that allows you to run JS on DOM ready...

(function () {
	function load2(){
		// put whatever you need to load on DOM ready in here
		document.getElementById("but3").addEventListener("click", doMore, false);
	}
	if (window.addEventListener) {
		window.addEventListener('DOMContentLoaded', load2, false);
	} else {
		window.attachEvent('onload', load2);
	}
} ());

Here is the some of the javascript source for the demo.. http://ie.microsoft.com/testdrive/Includes/Script/ReturnAndShareControls.js

It works well. Nice!!.. on google Chrome and IE 9.

Solution 5 - Javascript

i've updated the code of DOMAssistant library it works fine with me

var domReady = (function (){
  var arrDomReadyCallBacks = [] ;
  function excuteDomReadyCallBacks(){
       for (var i=0; i < arrDomReadyCallBacks.length; i++) {
         arrDomReadyCallBacks[i]();
       }
	   arrDomReadyCallBacks = [] ;
  }

  return function (callback){
    arrDomReadyCallBacks.push(callback);
     /* Mozilla, Chrome, Opera */
  	  if (document.addEventListener ) {
		  document.addEventListener('DOMContentLoaded', excuteDomReadyCallBacks, false);
	  }
	/* Safari, iCab, Konqueror */
	if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
		browserTypeSet = true ;
		var DOMLoadTimer = setInterval(function () {
			if (/loaded|complete/i.test(document.readyState)) {
				//callback();
				excuteDomReadyCallBacks();
				clearInterval(DOMLoadTimer);
			}
		}, 10);
	}
	/* Other web browsers */
	
	window.onload = excuteDomReadyCallBacks;
}
})()

Solution 6 - Javascript

document.addEventListener("DOMContentLoaded", function(e){
	console.log("dom ready");//output to web browser console
});

no JQuery needed for this. There is no need to pass the 3rd parameter on a DOMContentLoaded as this event has no parent to traverse the event. Also no need to get all fancy with what everyone else is saying. This will tell you when the DOM is fully loaded and ready to use. I LOLed when i noticed the DOM assistant lib. That lib is absolutely useless.

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading

addEventListener() is a great function for checking any event including DOM ready status. When using "DOMContentLoaded" the 3rd parameter in addEventListener() is not needed as this trigger has no parent item to pass the event too. In my above example you will notice the 2nd parameter is an anonymous function. You can also pass the name of a function into the 2nd parameter.

document.addEventListener([(string)event trigger], [function],[(boolean)traverse DOM tree]);

Another benefit to using this over JQuery is this will not break when you update JQuery.

Solution 7 - Javascript

jQuery doesn't use window.onload.

$(document).ready() waits until the DOM has loaded and can be traversed (the rest of the content may or may not be loaded by that point).

If you pull up the source for jQuery and sort through the mess, you'll find the work is done by the bindReady() method which has several different implementations for different browsers and only when all of those implementations fail does it fall back on listening for the load event for the window.

Solution 8 - Javascript

This is actually one of the biggest reasons most people use frameworks like jQuery because the solution to this is not consistent across browsers.

Solution 9 - Javascript

Try this:
Link: [onDomReady at GitHub](https://github.com/dsrdakota/onDomReady "Yes, this is mine...") or the source below:

if(document.ondomready == undefined) {
    document.ondomready = {};
    document.ondomready = null;
} else {
    document.ondomready=document.ondomready;
}
var oldonload=document.onload;
var isLaunched = 0;
document.onload = function() {	
    if(oldonload !== null) {
        oldonload.call();
    }
};
document.addEventListener("DOMContentLoaded", function onDom(evt) {
    var olddomready = document.ondomready;
    if(olddomready !== null) {
        if(isLaunched == 0) {
            olddomready.call(evt);
            isLaunched == 1;
            //We now launched the mapped DOMContentLoaded Event
        } else {
            //We already launched DOMContentLoaded Event
        }
    }
}, false);

I've already tested this on Opera 11.x/12.x. Not yet tested on others. Let me know if they do.

Note: I haven't yet uploaded the repository, but I will soon in my spare time.

Solution 10 - Javascript

If you want smaller libs which does only particular things, you could use libs in microjs. For the question at hand DOMStatic libs ready method can be used.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkristian nissenView Question on Stackoverflow
Solution 1 - JavascriptRyan WhealeView Answer on Stackoverflow
Solution 2 - JavascriptBlixtView Answer on Stackoverflow
Solution 3 - JavascriptDamon SmithView Answer on Stackoverflow
Solution 4 - JavascriptRandy SkretkaView Answer on Stackoverflow
Solution 5 - JavascriptYehiaView Answer on Stackoverflow
Solution 6 - JavascriptPatrick W. McMahonView Answer on Stackoverflow
Solution 7 - JavascriptJustin NiessnerView Answer on Stackoverflow
Solution 8 - JavascriptScott FoxView Answer on Stackoverflow
Solution 9 - JavascriptdsrdakotaView Answer on Stackoverflow
Solution 10 - JavascriptJerome AnthonyView Answer on Stackoverflow