Reputation: 3606
I have come across some code using $(window).ready()
that does dome UI resizing and positioning on HTML elements. I wondering why it is used? Is there an advantage to using it this way?
Are there any advantages over $(document).ready()?
Upvotes: 0
Views: 5465
Reputation: 780974
I looked at the jQuery 1.9.0 source code, and it doesn't look like the .ready()
method uses at the object it was applied to; it has document
hard-coded throughout it. So all $(anything).ready(...)
calls are equivalent.
Download the source code and see the definition of jquery.ready.promise
, this is where most of the work of $(...).ready()
is done.
The documentation makes it clear that $(window).ready()
doesn't have a defined meaning:
The
.ready()
method can only be called on a jQuery object matching the current document, so the selector can be omitted.
Currently the object is ignored, the above allows them to change this behavior in the future, since it shouldn't impact any correctly-written code.
Upvotes: 3
Reputation: 382130
The advantage of ready
over the load
event is that it fires as soon as the DOM is ready, without waiting for the distance resources (mainly the images) to be loaded. Usually you just want to be sure the elements are present, so that you can bind to them, but you don't need the distance resources to be loaded.
From the documentation :
In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed
$(window).ready()
and $(document).ready()
are equivalent.
From the source code :
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
You see that the argument isn't even used, it's just returned so that you can chain if you want. You could have done this :
$({}).ready(function(){
...
});
But you shouldn't worry and should use the shortcut :
$(function(){
// your code which needs the DOM here
});
Upvotes: 10