Difference between $ (callback) and $ (document) .ready (function)?

On the jQuery site, the description for $(callback) was that it behaves the same as $(document).ready(function) , but then the examples showed some differences between the two syntaxes. So I was wondering, does anyone know what is the difference between the two?

+4
source share
4 answers

There are no differences, and the documents show no difference:

All three of the following syntaxes are equivalent:

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

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

I think you are confused by an example showing jQuery(function($){ ... }); This is just a way to call $(handler) , without the $ conflict.

IE

 // Here `$` is used by another library jQuery(function($){ // Here `$` refers to jQuery }); 
+7
source
 $(document).ready(function() { // Handler for .ready() called. }); 

Which is equivalent to calling:

 $(function() { // Handler for .ready() called. }); 

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

+4
source

There is no difference except that the shortcut is very slightly slower as it must resolve the type of argument and then call $(document).ready . (Actually, the jQuery source code is very clean, so you can easily check for yourself - the $() calls to $.fn.init , which goes through several tests , then calls ready on line 177.)

+1
source

There is no difference. If you call $() with only one parameter - a function: $(some_function) - this means that it will call $(document).ready(some_function)

So for simplicity you can use:

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

PS Do not use this structure if you use different libraries (which may conflict with the $ variable). In these cases, use:

 jQuery(function(){ // your code }); 
0
source

All Articles