When should I use jQuery's document.ready function?

JavascriptJqueryDomEvent HandlingDocument Ready

Javascript Problem Overview


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:

  1. 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 inside document.ready?
  2. Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
  3. 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.

Javascript Solutions


Solution 1 - Javascript

In simple words,

> $(document).ready is an event which fires up when document 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,

  1. $(document).ready does not wait for images or scripts. Thats the big difference between $(document).ready and $(document).load

  2. 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 - Javascript

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 - Javascript

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 - Javascript

.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 - Javascript

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.

Solution 6 - Javascript

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.

$(document).ready(function(){
bindelement1();
bindelement2();
});

function bindelement1(){
$('el1').on('click',function...);
//you might make an ajax call here, then under complete of the AJAX, call this function or any other function again
}

function bindelement2(){
$('el2').on('click',function...);
}

Solution 7 - Javascript

I appended a link to a div and wanted to do some tasks on the click. I added the code below the appended element in the DOM but it did not work. Here is the code:

<div id="advance-search">
   Some other DOM elements
   <!-- Here I wanted to apppend the link as <a href="javascript:;" id="reset-adv-srch"><span class="bold">x</span> Clear all</a>-->
</div>

<script>
  $("#advance-search #reset-adv-srch").on("click", function (){
	 alert('Link Clicked');``
  });
</script>

It did not work. Then I placed the jQuery code inside $(document).ready and it worked perfectly. Here it is.

$(document).ready(function(e) {
    $("#advance-search #reset-adv-srch").on("click", function (){
		alert('Link Clicked');
	});
});

Solution 8 - Javascript

he ready event occurs when the DOM (document object model) has been loaded.

Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.

The ready() method specifies what happens when a ready event occurs.

Tip: The ready() method should not be used together with .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontim petersonView Question on Stackoverflow
Solution 1 - JavascriptJashwantView Answer on Stackoverflow
Solution 2 - JavascriptJustinView Answer on Stackoverflow
Solution 3 - JavascriptTom SarduyView Answer on Stackoverflow
Solution 4 - JavascriptDipakView Answer on Stackoverflow
Solution 5 - JavascriptelclanrsView Answer on Stackoverflow
Solution 6 - JavascriptPulkit MittalView Answer on Stackoverflow
Solution 7 - JavascriptSafeer AhmedView Answer on Stackoverflow
Solution 8 - JavascriptShrikant ShiledarView Answer on Stackoverflow