Document-ready: what is it and how do I use it?

jQuery code is often wrapped in jQuery(function($) { ... }); so that it only runs after the DOM has finished loading. 

<script type="text/javascript"> jQuery(function($) { // this will set the div's text to "Hello". $("#myDiv").text("Hello"); }); </script> <div id="myDiv">Text</div>

This is important because jQuery (and JavaScript generally) cannot select a DOM element that has not been rendered to the page. 

<script type="text/javascript"> // no element with id="myDiv" exists at this point, so $("#myDiv") is an

// empty selection, and this will have no effect $("#myDiv").text("Hello"); </script> <div id="myDiv">Text</div>

Note that you can alias the jQuery namespace by passing a custom handler into the .ready() method. This is useful for cases when another JS library is using the same shortened $ alias as jQuery, which create a conflict. To avoid this conflict, you must call $.noConflict(); - This forcing you to use only the default jQuery namespace (Instead of the short $ alias). 

By passing a custom handler to the .ready() handler, you will be able to choose the alias name to use jQuery

$.noConflict(); jQuery( document ).ready(function( $ ) { // Here we can use '$' as jQuery alias without it conflicting with other // libraries that use the same namespace $('body').append('<div>Hello</div>') });

jQuery( document ).ready(function( jq ) {

// Here we use a custom jQuery alias 'jq' jq('body').append('<div>Hello</div>') });

Rather than simply putting your jQuery code at the bottom of the page, using the $(document).ready function ensures that all HTML elements have been rendered and the entire Document Object Model (DOM) is ready for JavaScript code to execute. 

jQuery 2.2.3 and earlier 

These are all equivalent, the code inside the blocks will run when the document is ready:

$(function() { // code }); $().ready(function() { // code }); $(document).ready(function() { // code });

Because these are equivalent the first is the recommended form, the following is a version of that with the jQuery keyword instead of the $ which produce the same results:


jQuery(function() { // code });

jQuery 3.0


As of jQuery 3.0, only this form is recommended: 

jQuery(function($) { // Run when document is ready // $ (first argument) will be internal reference to jQuery // Never rely on $ being a reference to jQuery in the global namespace });

All other document-ready handlers are deprecated in jQuery 3.0. 


As of jQuery 3.0, the ready handler will always be called asynchronously. This means that in the code below, the log 'outside handler' will always be displayed first, regardless whether the document was ready at the point of execution. 

$(function() { console.log("inside handler"); }); console.log("outside handler");