45

Is it bad to have multiple $(document).ready(function() {}); on your page? I have a website where I load different things at different times. I fire off those partial postback functions inside $(document).ready() but i have about 4 or 5 on the page at once. Is this a bad practice? Specifically, will it cause any performance issues?

Matthew Slattery
  • 45,290
  • 8
  • 103
  • 119
codette
  • 12,343
  • 9
  • 37
  • 38

5 Answers5

33

This answer is no longer relevant. Please see other posts below for more up-to-date jQuery $.ready() impacts. This post is over 3 years old.

See: http://jsperf.com/docready/11

The answer is no! You can litter them as much as you want (note the word litter). They just become a queue of events that are called when the ready event is triggered.

http://www.learningjquery.com/2006/09/multiple-document-ready

Justin Van Horne
  • 1,322
  • 11
  • 15
11

The answer is actually "Yes it deters performance":

http://jsperf.com/docready/3

Maverick
  • 3,039
  • 6
  • 26
  • 35
  • 4
    You're drawing conclusions based on your opinion. The answer is that there is a performance hit (everything has a performance hit) and that hit should be weighed against the benefits of it. Even with IE8 it would take 20K $.ready calls to slow down my page by 1 second. The 50 - 100 that I do use would result in an increase of about 0.0025 seconds on IE or 0.000125 seconds on Chrome. – umassthrower May 09 '13 at 21:21
4

No it is fine to have as many as you want. A shorter, much more elegant way to do this is $(function(){}) though.

Matthew Slattery
  • 45,290
  • 8
  • 103
  • 119
Craig
  • 7,471
  • 4
  • 29
  • 46
1

If it's on the same page I would personally put them all in the same place so that you can't be caught out by forgetting one of the things happening on load.

I doubt the performance implications are that significant though. Have you tried benchmarking the page with them all together and apart?

Garry Shutler
  • 32,260
  • 12
  • 84
  • 119
-1

If any of them throw an exception, it blocks the rest from running. This can be very difficult to debug with code "littered" across multiple source files (esp. 3rd party libraries).