jQuery $(document).ready alternatives

jquery document.readyYou will no doubt already know that the $(document).ready function is jQuery’s way of executing your JavaScript code after the DOM has finished loading. The standard use looks like this:

$(document).ready(function(){
// your code here
});

Other JavaScript libraries have similar approaches and have saved the web from all manner of ugly behavioral code in HTML such as onClick and onLoad.

There are however some alternatives to $(document).ready that you may not be aware of:

1. Use shorthand

$(function(){
// your code here
});

This works in exactly the same way as the standard $(document).ready function and has the added benefit of being more concise. The minor downside is that the code becomes marginally more cryptic for those not familiar with the syntax. For the sake of a few extra characters the standard method is slightly easier for those who are new to jQuery.

2. Don’t use an anonymous function

$(document).ready(fooBar);

function fooBar()
{
// Your code here
}

In this method we explicitly state the function we want to execute when the DOM has finished loading. It is still using the normal jquery $(document).ready syntax but the fooBar function is called instead of using an anonymous function. The result is the same but the opening and closing brackets are less untidy.

By using this method your code is not encapsulated in an anonymous function and therefore your use of a global function will pollute the global namespace.

3. On ‘Window’ load

There is a lesser known option that waits for the whole page to load, including images. This is in comparison to normal $(document).ready which just waits for the DOM to load.

$(window).load(function(){
// Your code here
});

This obviously has its advantages if you need absolutely everything to have finished loading before your JavaScript runs. For everyday use however you will probably run into problems where your scripts will not work until all the assets have finished loading. This may annoy your users who will be wanting to interact with the page before it is ready.

4. Don’t use $(document).ready at all

There is a small performance hit in using $(document).ready so, if the code you have written does not need the DOM to have finished loading, consider not using the $(document).ready function at all.

This seems like a risky strategy however for a marginal speed improvement.

Additionally current wisdom suggests moving your JavaScript code to the end of the page, mainly for the speed improvements. An interesting side-effect of moving your JavaScript to the end of the page is that $(document).ready is often no longer necessary. It is important to remember that not all code can be moved to the bottom of the page, document.write calls for example are problematic.

So which is the best option?

Unless you are completely clear about the advantages & risks of each method I would suggest sticking to using the original $(document).ready function or the shorthand alternative. In most situations moving your JavaScript to the end of the document is probably a good idea too.

Update: 6th May 2013

Thanks to @UnseenRevolution in the comments

Use noConflict to prevent the $ from conflicting with other JavaScript libraries.

jQuery.noConflict();
(function($) {
  $(function() {
   // by passing the $ you can code using the $ alias for jQuery
   alert('Page: ' + $('title').html() + ' dom loaded!');
  });
})(jQuery);

11 Responses to jQuery $(document).ready alternatives

  1. JamsAlx says:

    I have been playing around with this and found that a mix of both .ready declaration and the shorthand version work best for me.

    I have found that nothing good comes from moving all you JS to the bottom, always seems to break or just act strange. But have persisted where I can.

    What’s your take in having no JS on a page and just a link to an external file, something I’m getting pushed to do, but I find it looses a lot of the context, when interacting with HTML elements?

  2. Russell says:

    I am encouraging the guys in our team to move all the js to external files, so yeah, I am deffo in favour of that.

    I have always been in the school of thought that it is prudent to have a good separation of content, style and behaviour.

    I am not over zealous about enforcing this as it makes sense in some situations, such as assigning data.

    One big reason I like them in a separate file is that our javascript files are consolidated and minified on the live site. Any js code which is inline will therefore not get this benefit.

  3. Jon Leek says:

    Guys, for those of you that do not already know… The shorthand version is not completely x-browser compatible. For instance, the shorthand version will work in Chrome, FF, Safari and IE9 but not in IE8 or older.

  4. Russell says:

    Hi Jon, not sure what you mean. The shorthand version works fine in older versions of IE.

  5. Lee says:

    Hi, I can’t find an answer to this anywhere (probably because I don’t know what to search for) but this seems a pertinent place to ask.

    You know the Google GA script? Well it used to be that you’d put that just before your closing body tag, then they changed it, and the latest version suggests placing in the head again. It looks like this:

    (function(){
        // blah blah blah
        document.createElement('script');
        // blah blah blah
    })();

    Now, I recognise that that’s an anonymous function call but given that it contains that line that I have left in, presumably it must only fire after the document is ready.

    I can’t however find anything to confirm that this method is a way of firing code when the document is ready. So, is that another way?

  6. Russell says:

    Hi Lee,

    You are right, that is simply an anonymous function and so will execute immediately by itself. It will not wait for the DOM to load.

    I believe it is recommended to place Google Analytics code in the head as it now loads in asynchronously. This means the tracking code can load in while the rest of the page is still being rendered. It also means that the code will track hits, even if the whole page hasn’t finished loading.

    Therefore it isn’t another way of waiting for the DOM to be ready, it is a way of loading in the code in parallel with the rest of the page content.

    Hope that helps.

    • Lee says:

      Ahh, I just figured document.createElement couldn’t be called on a dom that wasn’t already ready.
      Thanks for the info.

  7. Hi Russell,

    You may also want to include the jQuery Noconflict option to your list. This features prevents the $ from conflicting with other JavaScript libraries. Many people will see that when working with CMSs like WordPress.

    jQuery.noConflict();
    (function($) {
      $(function() {
       // by passing the $ you can code using the $ alias for jQuery
       alert('Page: ' + $('title').html() + ' dom loaded!');
      });
    })(jQuery);

    Awesome write up,
    Cheers!

  8. samuel says:

    Hello there! i have check ur article about document.ready(). i try to use it but it’s not working. here is the code

    One Love

    $(document).ready(function (){
      document.getElementById("sami_div").style.display='';
    })
         
    function one()
    {
     document.getElementById("xCard").value='Hello there'; 
    }

    Dear sami i'm glad u still here!

    any help will be appriciated

Leave a Reply

Your email address will not be published. Required fields are marked *