-1

I understand the premise of $(document).ready - in layman's terms, wait until the document object module is completely ready before executing this script - but what I don't understand is why all jQuery code can't just be run when the document is ready.

Do some functions need to be set up before the document finishes processing? Is it just an anomalous issue from the original structure when jQuery was written.

If anyone has a good answer to this, it would help my understanding as well as the understanding of many other jQuery users in the future.

worldofjr
  • 3,868
  • 8
  • 37
  • 49
  • possible duplicate of [Is $(document).ready necessary?](http://stackoverflow.com/questions/4643990/is-document-ready-necessary) – nietonfir Oct 19 '14 at 22:30
  • @nietonfir Not the same question is it. Thanks for not reading! – worldofjr Oct 19 '14 at 22:33
  • possible duplicate of [jQuery: Why use document.ready if external JS at bottom of page?](http://stackoverflow.com/questions/1438883/jquery-why-use-document-ready-if-external-js-at-bottom-of-page) – PeterKA Oct 19 '14 at 22:40
  • give example of something that, in your mind, can't be run ( or isn't run) when document is ready . Question is pretty vague without specifics – charlietfl Oct 19 '14 at 22:46

1 Answers1

3

If all jQuery code would run when the document is ready, it would have to queue up all calls until then. That would make every call before the ready event asynchronous, which would make everything more complicated.

Example:

var prefix = "A:";
$('.colA').text(function(i, t){ return prefix + t; });
prefix = "B:";
$('.colB').text(function(i, t){ return prefix + t; });

This will add the prefix A: to the text of the elements with class="colA" and B: to the text of the elements with class="colB".

If the calls were asynchonous, it would add B: to all the elements, because both assignments would run before any of the jQuery code.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005