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.
Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to
$(document).ready()
. The function we pass can just be an anonymous function.This will run the function that we pass to .ready() once the document is ready. What's going on here? We're using $(document) to create a jQuery object from our page's document, and then calling the .ready() function on that object, passing it the function we want to execute.
Since this is something you'll find yourself doing a lot, there's a shorthand method for this if you prefer — the $() function does double duty as an alias for $(document).ready() if you pass it a function:
This is a good reading: Jquery Fundamentals
You should bind all actions in document.ready, because you should wait till the document is fully loaded.
But, you should create functions for all actions and call them from within the document.ready. When you create functions (your global objects), call them whenever you want. So once your new data is loaded and new elements created, call those functions again.
These functions are the ones where you've bound the events and action items.