jQuery Document Ready - 最好将每个语句包装起来还是将所有语句包装在一个 document.ready 事件中?
我已经看到了两种方式,但哪种更好或者并不重要。
我觉得包装每个语句可能会更干净,但只是想知道如果您有 50 个语句,每个语句都有自己的 document.ready 事件处理程序,是否会有更多回调?
I have seen it both ways, but which is better or does it not matter.
I feel as though wrapping each statement might be cleaner, but just wondering if its more callbacks if you have 50 statements each with their own document.ready event handler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
jQuery 开发人员倾向于将所有内容都挂接到
$(document).ready
伪事件中。毕竟,您会发现大多数示例都使用了它。尽管
$(document).ready
非常有用,但它发生在页面渲染期间对象仍在下载时。如果您发现页面在加载时停滞,所有这些$(document).ready
函数可能就是原因。您可以通过将 jQuery 函数绑定到 $(window).load 事件来降低页面加载期间的 CPU 使用率,该事件在 HTML 调用的所有对象(包括内容)下载完成后发生。
此处或观看此视频
There is a temptation among jQuery developers to hook everything into the
$(document).ready
pseudo event. After all, it is used in most examples you will find.Although
$(document).ready
is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those$(document).ready
functions could be the reason why.You can reduce CPU utilization during the page load by binding your jQuery functions to the $(window).load event, which occurs after all objects called by the HTML (including content) have downloaded.
Read more about jQuery performance and best practices here or watch this video