两者的区别是什么
$(function(){ });
还有
$(document).ready(function() { });
什么都没有。
这个函数的行为就像 $(document).ready(), in that it should be used to wrap other $()
你可以在 source code中看到这一点:
rootjQuery = jQuery(document); ... } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }
$(function (){})是 dom 就绪的捷径
作为参数传递给 jQuery 构造函数的函数被绑定到文档就绪事件。
我用 $(function() {});是因为它更短。据我所知,这两种做法没有什么不同。
$(function() {});
Both are equivalent, the first is a shorthand form.
他们实际上是一样的,没有区别。
This is the native way.
$(document).ready(function() { // code });
这是前一个的简写。
$(function() { // code });
JQuery 源代码
} else if (jQuery.isFunction(selector)) { return rootjQuery.ready(selector); }
来自 来源
调用 $(document).ready(selector)可以保存一些 if 语句。
$(document).ready(selector)
尽管 jQuery 在内部缓存了 $(document),这可能会使 $(f)更快。
$(document)
$(f)
基准测试
我建议你读一读 这个。如你所见
All three of the following syntaxes are equivalent: $(document).ready(handler) $().ready(handler) (this is not recommended) $(handler)
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
So it's up to you and to what you prefer.
两者完全相同: 使用你喜欢的任何形式。
也就是说,我个人使用扩展形式 一直都是的原因很简单,那就是代码所做的事情是完全明显的。大致的概念是“自我文档化代码”。任何稍后访问该代码的人都会立即看到该代码将在 document的 ready事件上运行。使用简写形式时,您必须依靠代码的读者来理解其含义。
document
ready
我们遇到过 IE9不在 $(function (){})内运行函数的情况; 其方式或计时与 $(document)相同。就绪(函数(){}) ;
这个问题出现在我们读取查询字符串中的信息并在屏幕上处理和显示这些信息,或者使用它来处理表单的时候。一旦用 $(function ()缓存了信息,并且用户刷新了页面,IE9就会处理这些信息。但是在第一次运行时,没有一个是正确的。但是,一旦我们从 $(function (){}) ; 切换到 $(document)。() ,问题已经解决。我们什么都没改变。
I so look forward to the day I don't have to test for IE9 and lower.
JQuery 建议使用 $( fn )。
$( fn )
$(document).ready(function() {});或 $(document).on("ready", fn); will cause the function to be called when the document is ready, but only if it is attached before the browser fires its own 这使得它在许多情况下都不可靠, 尤其是在加载 jQuery 或其插件的地方 页面加载后异步。
$(document).ready(function() {});
$(document).on("ready", fn);
更多信息,请查看 移植