What is the difference between these jQuery functions?

What is the difference between

$(function(){ }); 

and

 $(document).ready(function() { }); 
+70
jquery
Apr 18 '10 at 15:38
source share
9 answers

Nothing.

This function behaves in the same way as $ (document) .ready (), since it must be used to transfer other $ ()

You can see this in the source code :

 rootjQuery = jQuery(document); ... } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } 
+53
Apr 18 '10 at 15:39
source share
 } else if (jQuery.isFunction(selector)) { return rootjQuery.ready(selector); } 

From source

Calling $(document).ready(selector) saves several if statements.

Although jQuery does caching $(document) internally, which can make $(f) faster.

Benchmarking

+15
Mar 03 '11 at 18:19
source share

Both are equivalent, the first is an abbreviated form.

+8
Mar 03 '11 at 18:17
source share

$ (function () {}) is a short environment for dom ready

The function passed as an argument to the jQuery constructor is bound to the document ready event.

+7
Apr 18 '10 at 15:40
source share

Both are equivalent: use whatever shape you like.

However, I personally always use the extended form $(document).ready(function(){}); for the simple reason that it is obvious what the code does. A rough idea is "self-documenting code." Anyone who arrives at the code later will immediately see that the code must be run in the document ready event. In short, you need to rely on the reader of your code that understands the meaning.

+7
Mar 03 '11 at 18:20
source share

I suggest you read this . as you can see

All three of the following syntaxes are equivalent:

$(document).ready(handler)

$().ready(handler) (this is not recommended)

$(handler)

So, it is up to you and what you prefer.

+6
Mar 03 '11 at 18:20
source share

They are almost the same. No difference.




This is a home way.

 $(document).ready(function() { // code }); 

And this is a reduction for the previous one.

 $(function() { // code }); 

jQuery source code

+4
03 Mar. '11 at 18:19
source share

We are faced with situations where IE9 does not start functions in $ (function () {}); in the same way or in time as $ (document) .ready (function () {});

The problem has raised its head for us specifically to read information from the query string and process and display this information on the screen or use it to process the form. IE9 would process the information as soon as it was cached using $ (function (), and the user refreshed the page, but it didn’t work the first time. However, as soon as we move from $ (function () {}) to $ (document ) .ready (), the problem has been fixed. We changed NOTHING else.

I look forward to the day when I do not need to test IE9 and below.

+4
Oct 08 '13 at 22:22
source share

I am using $(function() {}); because it is shorter. As far as I know, there is no difference between the two ways of this.

+2
Mar 03 '11 at 18:17
source share



All Articles