简体   繁体   English

Jquery - 超过1“$(document).ready”=脏代码?

[英]Jquery - More than 1 “$(document).ready” = dirty code?

is it OK to use the 是否可以使用

$(document).ready(function ()
{   

// some code

});

more than 1 time in the javascript code? 在javascript代码中超过1次?

是的,没关系,jQuery会将它们排队并合并到一个DOM准备好时调用的单个处理程序中。

Sure it is ok. 当然可以。 Sometimes you have no other option. 有时你别无选择。 especially when you have some included JS files with jQuery and some jQuery code in the page itself. 特别是当你有一些包含jQuery的JS文件和页面本身的一些jQuery代码时。

I find that having everything in one huge $(document).ready leads to messy code thats hard to read. 我发现在一个巨大的$(文档).ready中拥有所有内容会导致难以阅读的混乱代码。

I often prefer to split it up and place a separate $(document).ready() for every part of the system that needs stuff added to it. 我经常喜欢将其拆分并为需要添加内容的系统的每个部分放置一个单独的$(document).ready()。 This is especially nice for larger, modular, systems, where you dynamically add blocks of html, events and stuff. 这对于较大的模块化系统尤其有用,在这些系统中,您可以动态添加html,事件和内容块。

For me it all boils down to what is most beneficial for you as a developer in a certain case. 对我来说,这一切都归结为在某种情况下作为开发人员对您最有利的事情。

  • Small system, where it's easy to know what's going on: one $(document).ready() in your script. 小系统,很容易知道发生了什么:脚本中有一个$(document).ready()。
  • Large, modular, system: split it up as needed to have control of what's going on, and develop efficiently. 大型,模块化的系统:根据需要将其拆分,以控制正在发生的事情,并有效地发展。

But as @Codesleuth commented: very often you don't need to put stuff inside the $(document).ready(), you only need it when you need to be sure the DOM is in a consistant and known state for heavy manipulation etc. 但是正如@Codesleuth评论的那样:通常你不需要把东西放在$(document).ready()里面,你只需要确保DOM处于一致且已知状态以便进行大量操作等等。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM