$(document).ready 有必要吗? [英] Is $(document).ready necessary?

查看:30
本文介绍了$(document).ready 有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stackoverflow 中看到了这个问题,但觉得它根本没有得到解答.

I saw this question in stackoverflow but do not feel that it was answered at all.

是否需要$(document).ready?

我在页面底部链接了我所有的 javascripts,所以理论上它们都在文档准备就绪后运行.

I link all my javascripts at the bottom of the page so in theory they are all running after the document is ready anyways.

推荐答案

是否需要$(document).ready?

如果您将所有脚本放在 </body> 结束标记之前,那么您所做的就是完全相同的事情.

no

if you've placed all your scripts right before the </body> closing tag, you've done the exact same thing.

此外,如果脚本不需要访问 DOM,那么除了对其他脚本的可能依赖之外,它被加载到哪里都无关紧要.

Additionally, if the script doesn't need to access the DOM, it won't matter where it's loaded beyond possible dependencies on other scripts.

对于许多 CMS,您没有太多选择脚本的加载位置,因此使用 document.ready 事件是模块化代码的好形式.如果你在别处重用旧代码,你真的想回去调试它吗?

For many CMS's, you don't have much choice of where the scripts get loaded, so it's good form for modular code to use the document.ready event. Do you really want to go back and debug old code if you reuse it elsewhere?

附带说明:您应该使用 jQuery(function($){...}); 而不是 $(document).ready(function(){...}); 因为它强制别名为 $.

As a side note: you should use jQuery(function($){...}); instead of $(document).ready(function(){...}); as it forces the alias to $.

这篇关于$(document).ready 有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆