jQuery API

.ready()

.ready( handler ) Returns: jQuery

Description: Specify a function to execute when the DOM is fully loaded.

  • version added: 1.0.ready( handler )

    handlerA function to execute after the DOM is ready.

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

All three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)

There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
 // Handler for .ready() called.
});

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Example:

Display a message when the DOM is loaded.

<!DOCTYPE html>
<html>
<head>
  <style>p { color:red; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function () {
  $("p").text("The DOM is now loaded and can be manipulated.");
});
  </script>

</head>
<body>
  <p>Not loaded yet.</p>

</body>
</html>

Demo:

Support and Contributions

Need help with .ready() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .ready()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Anonymous
  • http://twitter.com/blogregeny Wyr

    Since $(document).ready(handler) is the equivalent of $(handler) why is the longer form more popular. Not only in tutorials, but in code written by most developers. The resulting code will be slightly shorter, and arguably more readable, since most of the time $(function(){ will be in a single line

  • jh

    because the longer form is more descriptive and human readable

  • Anonymous

    The fact that if you pass an event handler to document ready, after the event has already fired, it will be fired immediately, strikes me as incosistent with other events. Normally you need to wait for an event to be triggered, and if you schedule your handler too late then it never fires – this is a behaviour I would epect from event driven programming. What is the reason for the difference between .bind(‘ready’, handler) and .ready(handler)? I don’t think any other jQuery event shortcut function (like click) has this kind of difference. I think, unless there is a good reason for it, this API should be changed.

  • Anonymous

    Can anyone tell me if this is valid?
    I hate writing in the $(document).ready(function(){

    });
    format so I would prefer to do something like…

    function jqtest()
    {

    }

    $(document).ready(jqtest());

    or is it affected by the same problem as a callback? (http://docs.jquery.com/How_jQuery_Works#Callback_with_arguments)

    $(document).ready(jqtest()); AND $(document).ready(function(){ jqtest();} ); both work however the timing of the former is noticably faster than the latter, leading me to believe that the jqtest function is being fired before the document is in fact ready.

    Can anyone enlighten?

  • http://www.sharonminsuk.com/ Sharon Minsuk

    Though I’m fairly new with jQuery, it looks to me like what you really want is:

    $(document).ready(jqtest);

    Note the pair of parens I removed compared to your version. The .ready() function takes a function as an argument. The anonymous function:

    function(){…}

    is a function DECLARATION (which is what .ready() wants), whereas this:

    jqtest()

    is actually a function CALL, which executes the code you previously declared and returns the result. But the name ‘jqtest’ without the parens is the name of the function you declared, and so could substitute for the anonymous function as the argument to .ready().

    In your version, you’re right, the jqtest function is being executed as soon as that line is encountered (and likely passing an argument of the wrong type to the .ready() function, too). In contrast, if you pass just the name, then jqtest() is executed later, when the ready event fires.

  • Anonymous

    just take off the () from:
    $(document).ready(jqtest);

    cause this way the reference is used and not the result of calling the method contained

    Long explanation:
    When you use () it means you are invoking the method contained on variable jqtest, but when you pass only the variable the reference will be passed.
    to understand better you can do the following test:
    myAlert = alert;
    myAlert(“Text”);

  • Anonymous

    Thanks Sharon, I had only just started JQuery that day myself, what you have said seems to be right.

    My test page is loading properly now and while I do understand why the () makes a difference now, I still dont understand the logic of _why_ the JQuery interpreter would execute a callback function (call or declaration) before the callback was made.

    Prehaps it creates a little more flexibility in the whole system so that variables that may change before the callback can be processed, smarter programmers than me probably know ;)

    Thanks again

    -Pat

  • http://www.sharonminsuk.com/ Sharon Minsuk

    Actually, it doesn’t have anything to do with jQuery; it’s how the syntax of Javascript (and other languages too, for that matter) works. A call and a declaration are two completely different things. A function that takes a callback as an argument (the way ready() takes your jqtest as an argument) is specifically asking for a reference (or pointer) to a function. It’s saying “just tell me where the function is, so I can remember that and call it later”.

    When you add the parens, you’re the one who’s telling it to execute the function immediately. That’s what they mean!

    To put it another way: when you use jqtest alone, .ready() sees that you’re handing it what it wants, a function. When you add the parens, .ready() doesn’t even see that jqtest is there; it only sees that you’ve handed it, say, a string (if, for example, jqtest() returns a string). It doesn’t know where that string came from. The execution of your function is a done deal before .ready() ever gets involved. It’s all about how the language evaluates expressions.

    Make sense?

  • john

    I have $(document).ready(function{ }); and i have onLoad function for body. Here my requirement is to invoke $(document).ready() after onLoad.
    Is there any way to get my requirement done?

  • http://indir.biz/ indir

    jqtest() is not callback, its return mixed value.

  • http://www.wooliet.com WoolieT

    @john – I've created a plugin that might work for you. I've got a BitBucket repo setup here:

    http://bitbucket.org/wooliet/readyagain

  • Kyle

    Anyone know of a way to execute something reliably on $(document).ready() in Chrome/Chromium?
    I've noticed that because of the multi-threading (at least this is my theory), the DOM isn't properly loaded approx 1/3 of the time. I'm doing the following:

    $(document).ready(function(){
    $('.triangle').each(function(){
    var dWidth = $(this).css('width');
    $(this).text(dWidth);
    });
    });

    when it works properly, it puts the pixel-width of the element. Otherwise, it puts the pixel width of the document in every .triangle.

  • Kyle

    Figured out a fix for it:
    function widthCheck(){
    $('.triangle').each(function(){
    var dWidth = $(this).css('width');
    $(this).text(dWidth);
    });
    }
    $(document).ready(function(){
    window.onload = widthCheck;
    //other codestuffs irrelevant to this example follows……
    });

  • Paul

    I think google chrome (5.0.375.125) is firing this event before images have loaded

  • Xfsunoles

    You can do window.onload = function() {
    }

  • Guest

    Why isn’t jQuery(callback) included in the list of syntaxes that are equivalent?

    “This function behaves just like $(document).ready()”

  • http://www.exteon.ro Dinu

    This gets fired for every frame on the page; How to tell which frame triggered it, and/or how to disable bubbling?

  • Bill

    Because “shorter” and “readable” are usually opposites, not synonymous like you imply. The more verbose syntax makes it clear what’s going on, so the code is effectively self-documenting.

  • http://www.learningjquery.com/ Karl Swedberg

    It is. It's the third bullet: $(handler) is the same thing as jQuery(callback).

  • Graham

    Looks like .ready() fires not only when page initially has settled the DOM, but apparently also after changes to the DOM. This is an issue if your ready handler changes the DOM. That will result in ready() firing more than once. It may result in an endless loop if each invocation adds yet more to the DOM. Firefox and IE behave differently to this, including different error messages, and leaving the page display in different states. So, if ready() modifies the DOM, then it would be wise to have a way to check whether ready has already been fired. — gwideman

  • Graham

    Replying to self: Well it appears that part of the problem is not that the ready function fires again (though that is possible aparently), but that changing the DOM causes the script that _creates_ the ready function to fire again, adding an additional ready function, etc etc. This seems to happen if the javascript is embedded in the html at a point beyond (or contained in) the part of the DOM that the ready handler modifies. (Obviously would be better to put script that creates a ready function in the document head, but in this case that’s not an option.) Problem fixed by checking a global flag variable to be undefined before executing jQuery(document).ready(…).

  • http://www.nexxar.com Nick (of Nexxar)

    I have found a way to make the execution of jQuery.ready() happen much earlier on IE, avoiding flickering. (see: http://blog.nexxar.com/2010/10/07/speeding-up-jquery-ready-on-ie/)

    Put the following code at the end of the HTML page:
    <script type=”text/jscript”>

    </script>

  • Nick (of Nexxar)

    this should be inside the script tag:
    try{jQuery.ready();}catch(e){}

    The script tag must be at the end of the HTML code, right before the closing body tag.

  • http://www.nexxar.com Nick (of Nexxar)
  • nz

    Is it possible to test the 'ready' even to see if a particular handler has already been bound to it? I have some reusable components where multiple instances can appear on one page. Each requires the handler to be bound to ready, but when it is added multiple times it causes problems. Is there a way to test if its been bound? or should i use some other book keeping method?

  • http://www.nexxar.com Nick (of Nexxar)

    (all my posts to explain this have been removed – I am trying again)

    this code is useful to make jQuery.ready() called much earlier on IE. jQuery simulates the non existing “DOMContentLoaded” event on IE, but the used mechanism fires much later than the event used on other browsers. Page flickering occurs, especially if you are replacing any texts with sIFR flash.

    On the other hand IE creates the DOM tree while parsing the HTML page. At the end of the page, all the DOM is already available. If you add the code to the end of the page, (using type=”text/jscript” with the script-tag that only IE will execute it), then jQuery.ready() will be executed much earlier with the DOM tree ready for manipulation.

    For more explanation, visit my blog on my homepage and read the article from 2010-10-07.

  • Yogesh

    Hi,

    Kindly give an idea for the following case.

    I have a page with jquery validation. I used .ready() on page.

    Next i have one popup window, which invokes on clicking the button on the page(present on page.)

    In this popwindow I am doing validations for some controls (user-controls).All things are working fine and validating ok.

    But I facing problem,

    When i click cancel button on popupwindow, Main page validation is not working.

  • Yogesh

    Hi,

    Kindly give an idea for the following case.

    I have a page with jquery validation. I used .ready() on page.

    Next i have one popup window, which invokes on clicking the button on the page(present on page.)

    In this popwindow I am doing validations for some controls (user-controls).All things are working fine and validating ok.

    But I facing problem,

    When i click cancel button on popupwindow, Main page validation is not working.

  • Pratheep Velicherla

    Hi I am new to jQuery.I try to use the bellow code it is behaving differently in different browsers(IE,FF).
    function test() {
    // here I am using the $ as prototype
    alert($('divid').show);
    //here I am using jQuery as jQuery
    alert(jQuery('#divid').show);
    }
    jQuery(document).ready(function(jQuery){
    test();
    }

    I used the jQuery.noConflict(); for making the library non conflict.

  • Markus

    It probably would have been even easier if you used the .load event instead of the .ready event. To quote the above:
    “In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.”

    Since your code requires the 'width' property of the element in question, using load instead of ready would ensure that the content was fully loaded before you attempted to manipulate it.

  • Hgdhjgd

    Type your comment here.may result in an endless loop if each invocation adds yet more to the DOM. Firefox and IE behave differently to this, including different error messages, and leaving the page display in different states

  • ThomPatterson

    I came here looking to see if this was expected behavior, it struck me as odd. I came across this while dynamically loading an external JS, I noticed that $(document).ready() in the newly loaded JS was firing.

  • http://www.google.com/profiles/james.telfer JT

    This is because, unlike other events, the ready event will only fire once. Without this behaviour you would have to check: if (ready) { doImmediate() } else { bind }. The current behaviour simplifies the API (and use thereof) and preserves the intent of the event: one that guarantees that the handlers are fired once and only once, and after the DOM is ready.

    So no, it makes a lot of sense, and it should very definitely not be changed.

  • Deli

    number 1. $(document).ready(function(){
    …….
    });

    number 2.$(document).ready(function(){
    …….
    });

    If number 1 error arises, number 2 can not execute.

  • Deli

    number 1. $(document).ready(function(){
    …….
    });

    number 2.$(document).ready(function(){
    …….
    });

    If number 1 error arises, number 2 can not execute.

  • Pprosenjit

    thanx .. its very friendly

  • Pprosenjit

    thanx .. its very friendly

  • Pprosenjit

    thanx .. its very friendly

  • Pprosenjit

    thanx .. its very friendly

  • Pprosenjit

    thanx .. its very friendly

  • http://twitter.com/i_loops Infinite Loops

    There doesn't seem to exist a version with custom eventData of this function, unlike other callbacks. Correct me if I'm wrong… IMHO, it would be nice if such a version existed.

  • c0debreaker

    looks like good