RSS Feed

DomReady is For the Weak



The first thing we learned from JavaScript libraries is to be afraid of the DOM. The common recommendation is to wrap DOM-related code in a function which gets called only after the domready/ready/readystatechange event is fired— By then all elements should be available in the document.

Welcome to 2011

Truth is, if you do things right there's no justification for using `ready`. Performance experts recommend putting all scripts towards the end of the page, which implies when they run all elements would already be in place.

It's not that ready delays your scripts by a lot if they're already at the bottom - Just about 10ms in a modern browser. But if you can simplify and reduce your code, why not? Delaying your functions until the ready event is fired is good if you don't control the host page, for example if you write a plugin or js library. But iin other cases, you just make it easier for yourself to be lazy and leave scripts at the top.

Delaying until ready without using a library

Do you have code which has to appear before the end of the page, but could or should wait until the dom is ready?  Would you like to delay it without having to load jQuery or another DOM library? First of all, there are tiny libraries like domready which gives you just that. Or you could push all these functions into a queue, and then process it when the dom is ready, like so:

<script>var _later = [];</script>
    $('*').css('color', 'red');
    $('body').prepend('<span>Hello World</span>');
_later.push(1, true, null,
    undefined, 'hehe', {awesome: true},
    function(){$('span').css('background', '#fed')});
</script><script src="jquery.js"></script><script>
    $.each(_later, function(i, func){
        typeof func == 'function' && func();

For further reading, notice Alex Secton, who warned about the matter before, and Kyle Simpson (of LABjs fame) who Discussed some related edge-cases where domready actually breaks an application.

Related Content

What do you think?