What is the difference between:
$(document).ready(initialize);
and
$(document).on('ready', initialize);
To me they seem to work in the same way.
What is the difference between:
$(document).ready(initialize);
and
$(document).on('ready', initialize);
To me they seem to work in the same way.
Share Improve this question edited Dec 3, 2021 at 2:43 informatik01 16.4k11 gold badges78 silver badges108 bronze badges asked Nov 27, 2012 at 17:04 Lorraine BernardLorraine Bernard 13.4k23 gold badges85 silver badges137 bronze badges 1- 3 One uses a method directly, the other proxies through a helper method. – Sampson Commented Nov 27, 2012 at 17:06
2 Answers
Reset to default 18$(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
TL;DR
$(document).on('ready', ...)
is deprecated since it does not execute callbacks bound after the DOM was pletely parsed. It gets event object as first argument.$().ready()
gets passed a reference tojQuery
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 theready
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 pletely 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");
}