Lorraine Bernard
Lorraine Bernard

Reputation: 13400

What is the difference between $(document).ready(initialize) and $(document).on('ready', initialize)?

What is the difference between:

$(document).ready(initialize); 

and

$(document).on('ready', initialize); 

To me they seem to work in the same way.

Upvotes: 18

Views: 3769

Answers (2)

Felix Kling
Felix Kling

Reputation: 816354

TL;DR

  • $(document).on('ready', ...) is deprecated since it does not execute callbacks bound after the DOM was completely parsed. It gets event object as first argument.

  • $().ready() gets passed a reference to jQuery as first argument.


Detailed answer

$(document).on('ready', initialize);

This expression is binding a ready event handler to document, like you would expect from any other event handler. Using this to listen to DOM ready is deprecated as of jQuery 1.8:

There is also $(document).bind("ready", handler), deprecated as of jQuery 1.8. This behaves similarly to the ready method but 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.

Note that ready is a custom event, and triggered by jQuery internally. That also means that you can trigger it manually, which might mess things up.


$(document).ready(initialize);

This expression does not really bind an event handler. jQuery.fn.ready is a dedicated method to register callbacks to be run when the DOM was completely parsed. jQuery is adding the callback to a promise object and it does not matter which selector you pass to $.

Additionally, the callback gets passed a reference to the jQuery object instead of an event object.


The follwoing part of the source code nicely shows that callbacks registered like this are handled differently:

// If there are functions bound, to execute
readyList.resolveWith(document, [jQuery]);

// Trigger any bound ready events
if (jQuery.fn.trigger) {
    jQuery(document).trigger("ready").off("ready");
}

Upvotes: 8

antonjs
antonjs

Reputation: 14318

$(document).on('ready',initialize); will not work if the DOM is already ready when the file is executed.

$(document).ready() has a special handling for this: it ensures it is always called

Upvotes: 18

Related Questions