On the jQuery site, the description for $(callback)
was that it behaves the same as $(document).ready(function)
but then the examples showed some differenc开发者_开发问答es between the two syntaxes. So I was wondering, does anyone know exactly what the differences between the two are?
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
});
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
http://api.jquery.com/ready/
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.)
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
});
精彩评论