What's the difference between:
$(document).ready(function() {// Do something});
and
$(function() {//Do something});
in jQuery?
What's the difference between:
$(document).ready(function() {// Do something});
and
$(function() {//Do something});
in jQuery?
If I try in short then, they are alias. They are equivalent.
$(document).ready(function() {
})
$().ready(function() {
// this is not recommended
})
$(function() {
});
All are same.
jQuery developers recommend using:
$(document).ready(function() {
});
Why $().ready()
not recommend see Why "$().ready(handler)" is not recommended?
There isn't.
From the jQ API:
All three of the following syntaxes are equivalent:
$(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
are equivalent.
Actually, you can call .ready(handler)
on any jQuery object, no matter what it contains, and it will do the same thing:
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
They are the same(means they do the same thing). Check these lines from doc
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
And actually $(handler)
is an hardcoded shortcut to $(document).ready(handler)
. In the source code here http://code.jquery.com/jquery.js if you seach for rootjQuery
you will soon find these line
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
Or check this link https://github.com/jquery/jquery/blob/37ffb29d37129293523bf1deacf3609a28b0ceec/src/core.js#L174 to find out
Means if the passed selector
is a function, then it is used as $(document).ready(
handler.
Also check Which JQuery document.ready is better?