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.
In simple words,
Suppose you have placed your jQuery code in
headsection and trying to access adomelement (an anchor, an img etc), you will not be able to access it becausehtmlis interpreted from top to bottom and your html elements are not present when your jQuery code runs.To overcome this problem, we place every jQuery/javascript code (which uses DOM) inside
$(document).readyfunction which gets called when all thedomelements can be accessed.And this is the reason, when you place your jQuery code at the bottom (after all dom elements, just before
</body>) , there is no need for$(document).readyThere is no need to place
onmethod inside$(document).readyonly when you useonmethod ondocumentbecause of the same reason I explained above.EDIT
From comments,
$(document).readydoes not wait for images or scripts. Thats the big difference between$(document).readyand$(document).loadOnly code that accesses the DOM should be in ready handler. If it’s a plugin, it shouldn’t be in the ready event.