2

What's the difference between:

$(document).ready(function() {// Do something});

and

$(function() {//Do something});

in jQuery?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Basil Musa
  • 8,198
  • 6
  • 64
  • 63

4 Answers4

4

If I try in short then, they are alias. They are equivalent.

NOTE

$(document).ready(function() {

})


$().ready(function() {
  // this is not recommended
}) 

$(function() {

});

All are same.


More

jQuery developers recommend using:

$(document).ready(function() {

});

Why $().ready() not recommend see Why "$().ready(handler)" is not recommended?

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
3

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)

http://api.jquery.com/ready/

FreeMemory
  • 8,444
  • 7
  • 37
  • 49
3
$(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;
},
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

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.

http://api.jquery.com/ready/

Also check Which JQuery document.ready is better?

Community
  • 1
  • 1
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57