tags:

views:

113

answers:

3

Hi,

is it OK to use the

$(document).ready(function ()
{   

// some code

});

more than 1 time in the javascript code?

Thanks in advance! Peter

+11  A: 

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

Darin Dimitrov
Or it will fire them off immediately if the DOM is already ready. :)
Kevin
Thank you very much!
Peter
But don't use them just because you can. If your code can run on the document if it's not ready, sometimes it's best to let it.
Codesleuth
+1  A: 

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.

Stefanvds
A: 

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.

thomasmalt