When should I use jQuery's document.ready function?
Solution 1
In simple words,
$(document).ready
is an event which fires up whendocument
is ready.
Suppose you have placed your jQuery code in head
section and trying to access a dom
element (an anchor, an img etc), you will not be able to access it because html
is 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).ready
function which gets called when all the dom
elements 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).ready
There is no need to place on
method inside $(document).ready
only when you use on
method on document
because of the same reason I explained above.
//No need to be put inside $(document).ready
$(document).on('click','a',function () {
})
// Need to be put inside $(document).ready if placed inside <head></head>
$('.container').on('click','a',function () {
});
EDIT
From comments,
$(document).ready
does not wait for images or scripts. Thats the big difference between$(document).ready
and$(document).load
Only code that accesses the DOM should be in ready handler. If it's a plugin, it shouldn't be in the ready event.
Solution 2
Answers:
jQuery's .on() method: I use the .on() method for AJAX quite a bit (dynamically creating DOM elements). Should the .on() click handlers always be inside document.ready?
No, not always. If you load your JS in the document head you will need to. If you are creating the elements after the page loads via AJAX, you will need to. You will not need to if the script is below the html element you are adding a handler too.
Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
It depends. It will take the same amount of time to attach the handlers, it just depends if you want it to happen immediately as the page is loading or if you want it to wait until the entire doc is loaded. So it will depend what other things you are doing on the page.
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)?
It's essentially it's own function so it can only access vars declared at a global scope (outside/above all functions) or with window.myvarname = '';
Solution 3
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.
$(document).ready(function() {
console.log('ready!');
});
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:
$(function() {
console.log('ready!');
});
This is a good reading: Jquery Fundamentals
Solution 4
.ready() - Specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
// Handler for .ready() called.
});
Here is a List of all jQuery Methods
Read on Introducing $(document).ready()
Solution 5
To be realistic, document.ready
is not needed for anything else than manipulating the DOM accurately and it's not always needed or the best option. What I mean is that when you develop a large jQuery plugin for example you hardly use it throughout the code because you're trying to keep it DRY, so you abstract as much as possible in methods that manipulate the DOM but are meant to be invoked later on. When all your code is tightly integrated the only method exposed in document.ready
is usually init
where all the DOM magic happens. Hope this answers your question.
Related videos on Youtube
tim peterson
web programming-javascript, php, mysql, css, html-is my thang
Updated on August 07, 2022Comments
-
tim peterson over 1 year
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.-
Yinda Yin over 11 yearsBecause if the DOM is not ready, you may get unexpected results, that's all.
-
jd_7 over 11 years2.- Well i use outside just to debug and can to call some var/function by console,
-
tim peterson over 11 years@RobertHarvey what kind of "unexpected" results? can you provide an example?
-
Yinda Yin over 11 yearsYou try to modify an element or attribute that hasn't made it to the DOM yet.
- jQuery's
-
Jashwant over 11 years@Dipaks Yes, why not ? We are just very used to use
$(document).ready
. See this -
elclanrs over 11 yearsAs long as you load jQuery in the
head
and you're scripts after the elements being manipulated,document.ready
is not needed. Images are a special case though... -
tim peterson over 11 years@elclanrs See my updated question. I'm loading jQuery at the bottom of my HTML page with my app-specific code right after that.
-
tim peterson over 11 years@Jashwant how about performance differences of dom.ready vs. not? Are those relevant?
-
Jashwant over 11 yearsI dont think there's much of a performance difference (there were performance degradation in case of
live
buton
works differently). You can always use jsperf. If you are putting jQuery code at bottom, why usingdom.ready
? If not more, it at least increases a functional call. -
Ruan Mendes about 11 yearsWe don't put all
jQuery
code in the ready handler. Only code that accesses the DOM. If it's a plugin, it shouldn't be in theready
event -
Dinesh over 9 yearsvery nice explained bro...+1
-
John Magnolia over 9 yearsNot to be confused with
(function($){ })(jQuery);
which wraps your code so that $ is jQuery inside that closure -
Colin R. Turner almost 9 yearsTHAT is why we love this site. Thank you. 1++ :)
-
Admin about 7 yearsI'm not sure am I right, but when you put event inside of document.ready, it will fail. Is this real? (please, someone, protect this question, too much of +1 comments...)
-
PirateApp over 5 yearsupvoted! if your script is at the bottom of body, why do you need document.ready?
-
Jashwant over 5 yearsYou don't need
document.ready
if you script is placed after the DOM elements it is going to use. If it is at the bottom of body, you don't needdocument.ready
at all.