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

試著忘記壹切 提交于 2019-12-07 07:13:43

问题


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?


回答1:


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
});



回答2:


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

Which is equivalent to calling:

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

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




回答3:


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.)




回答4:


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
});


来源:https://stackoverflow.com/questions/7068916/difference-between-callback-and-document-readyfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!