I was told to use document.ready when I first started to use Javascript/jQuery but I never really learned why.
Might someone provide some basic guidelines on when it makes sense to wrap javascript/jquery code inside jQuery's document.ready
?
Some topics I'm interested in:
- jQuery's
.on()
method: I use the.on()
method for AJAX quite a bit (typically on dynamically created DOM elements). Should the.on()
click handlers always be insidedocument.ready
? - Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
- Object scope: AJAX-loaded pages can't access objects that were inside the prior page's document.ready, correct? They can only access objects which were outside document.ready (i.e., truly "global" objects)?
Update: To follow a best practice, all my javascript (the jQuery library and my app's code) is at the bottom of my HTML page and I'm using the defer
attribute on the jQuery-containing scripts on my AJAX-loaded pages so that I can access the jQuery library on these pages.