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 exactly what the differences between the two are?
-
What differences are you talking about?Felix Kling– Felix Kling2011年08月15日 18:37:23 +00:00Commented Aug 15, 2011 at 18:37
4 Answers 4
There are no differences, and the docs don't show any 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 the example showing jQuery(function($){ ... });
Which is just a way of calling $(handler), with no $ conflict.
IE.
// Here `$` is used by another library
jQuery(function($){
// Here `$` refers to jQuery
});
Comments
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
Comments
There is no difference at all, except that the shortcut is very slightly slower as it has to decide the type of the argument and then call $(document).ready. (Actually the source code of jQuery is very clean so you can easily check for yourself - $() calls $.fn.init, which goes through a couple of tests then calls ready at line 177.)
Comments
There is no difference.
If you call $() with just one parameter - a function: $(some_function) - it means, that it will call $(document).ready(some_function)
So, for simplicity, you could use:
$(function(){
// your code
});
P.S. Don't use this structure if you are using different libraries (that can conflict with $ variable). In these cases use:
jQuery(function(){
// your code
});
Comments
Explore related questions
See similar questions with these tags.