9

is it OK to use the

$(document).ready(function ()
{   

// some code

});

more than 1 time in the javascript code?

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Peter
  • 11,413
  • 31
  • 100
  • 152
  • 2
    I suggest to use the shorthand $(function(){ /* Some code */ }) – Babak Bandpay Sep 17 '10 at 09:19
  • duplicate of [jQuery - is it bad to have multiple $(document).ready(function() {});](http://stackoverflow.com/questions/1148241/jquery-is-it-bad-to-have-multiple-document-readyfunction) – David Cary Oct 03 '12 at 18:07

3 Answers3

11

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Or it will fire them off immediately if the DOM is already ready. :) – Kevin Sep 17 '10 at 08:12
  • 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 Sep 17 '10 at 08:15
1

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
  • 5,868
  • 5
  • 48
  • 72
1

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
  • 1,718
  • 11
  • 15