开发者

Jquery - More than 1 "$(document).ready" = dirty code?

is i开发者_如何学JAVAt OK to use the

$(document).ready(function ()
{   

// some code

});

more than 1 time in the javascript code?


Yes, it is OK, jQuery will queue and merge them into a single handler called when the DOM is ready.


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.


I find that having everything in one huge $(document).ready leads to messy code thats hard to read.

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. This is especially nice for larger, modular, systems, where you dynamically add blocks of html, events and stuff.

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.
  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜