jQuery - is it bad to have multiple $(document).ready(function() {});

后端 未结 5 799
孤街浪徒
孤街浪徒 2020-11-27 05:56

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 p

相关标签:
5条回答
  • 2020-11-27 06:31

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

    0 讨论(0)
  • 2020-11-27 06:36

    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?

    0 讨论(0)
  • 2020-11-27 06:40

    The answer is actually "Yes it deters performance":

    http://jsperf.com/docready/3

    0 讨论(0)
  • 2020-11-27 06:42

    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

    0 讨论(0)
  • 2020-11-27 06:48

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

    0 讨论(0)
提交回复
热议问题