$(document).ready是否必要? [英] Is $(document).ready necessary?

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

问题描述

我在stackoverflow中看到了这个问题,但根本感觉不到答案.

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

$(document).ready是否必要?

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

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天全站免登陆