Differences between document.ready and $function
Solution 1
They are the same. Check out the jQuery .ready()
docs. Here's a quote from the docs:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Solution 2
There is no difference in functionality between your examples - they both bind to DOM ready.
For reference, there are two points at which you can bind your jQuery code.
The first will execute when the DOM is ready (both are equivalent):
// full example
$(document).ready(function() {
// code...
});
// shortened
$(function() {
// code...
});
// ES6 example with $ aliased, note this is not supported in IE
jQuery($ => {
// code...
});
The second will execute when the page has finished loading all images, stylesheets etc.
$(window).on("load", function() {
// code...
});
The second is useful when you need to get the width()
or height()
of an image. These properties are only available once the image has completely downloaded to the client system.
Also note that $(window).load(fn);
is now deprecated and should no longer be used.
Solution 3
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Matt Morey
Updated on February 16, 2022Comments
-
Matt Morey about 2 years
Possible Duplicate:
What is the difference between these jQuery ready functions?
jquery: Choosing a document.ready methodWhat is the difference between doing this
$(function() { $("a").click(function(event){ alert("Thanks for visiting!"); }); });
and this
$(document).ready(function(){ $("a").click(function(event){ alert("Thanks for visiting!"); }); });
-
James Hill about 11 yearslol. Never ceases to amaze me. Down-voted for a correct answer and a quote from the docs :)
-
MarkDBlackwell almost 11 years
-
JorgeeFG over 9 yearsIF they are equivalent, why isn't one recommended?
-
Mark Schultheiss over 4 yearsfor clarity as of this date the doc says the
$(handler)
is recommended i.e. often seen as$(function(){});
with the code in that function body