
The jQuery Document Ready is an event that executes JavaScript or jQuery code only after the HTML document has been completely loaded and its DOM (Document Object Model) has been created. In simple words, it ensures that all HTML elements are available before jQuery tries to access or manipulate them.
$(document).ready(function() {
alert('DOM is Ready');
});
We can also use the shorthand $() for $(document).ready():
// Shorthand for $( document ).ready()
$(function() {
alert('DOM is Ready');
});
Page Contents
When a browser loads a web page, it does not show everything at once. It works through the page in stages:
The $(document).ready() method runs your code at step 3. At that point every HTML element exists and can be selected and changed safely, and you do not have to wait for the images to finish loading.
jQuery can only work with elements that already exist in the DOM. If your script runs before the browser has reached a particular element, then selectors like $(“#myButton”) find nothing, and any code that depends on them silently fails. Wrapping your code in $(document).ready() removes this problem, because the code waits until the DOM is complete.
This example shows how to attach a click event handler to a button using jQuery. The handler is placed inside the $(document).ready() method, so it runs only after the DOM has fully loaded.
$(document).ready(function(){
$("button").click(function(){
alert('Button is Clicked');
});
});
Note – In the above code, if you do not place the button click event inside the document ready function, then your code will not execute.
Therefore place all your codes inside jQuery Document Ready function.
These two are often confused because both run code after the page has loaded. The difference is when they run. As explained above, the browser fires DOMContentLoaded first, when the DOM is built, and the load event later, when every image, stylesheet and iframe has finished downloading.
| $(document).ready() | $(window).on(“load”) | |
|---|---|---|
| Fires when | The DOM is fully built | The whole page and all its resources are loaded |
| Waits for images and CSS? | No | Yes |
| Browser event | DOMContentLoaded | load |
| Speed | Earlier, so the page feels responsive sooner | Later, after the slowest image finishes |
| Multiple handlers allowed? | Yes, they run in the order they were added | Yes, they run in the order they were added |
| Typical use | Attaching events, selecting and changing elements | Code that needs image sizes, or that depends on all resources |
$(document).ready(function () {
console.log("1. DOM is ready");
});
$(window).on("load", function () {
console.log("2. Page fully loaded (images, CSS, etc.)");
});Open the browser console and you will always see message 1 first. On a page with large images, there can be a noticeable gap before message 2 appears.
Use $(document).ready() for almost everything, such as binding click events, reading form values or adding and removing elements. Use $(window).on(“load”) only when your code really depends on resources being fully loaded. A common example is reading the width and height of an image, which is not known until the image has downloaded.
The best way to understand why $(document).ready() matters is to see what goes wrong without it. Here is a page where the jQuery code sits in the <head>, before the button exists.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// The browser has NOT reached the button yet
console.log("Buttons found: " + $("#btnSave").length);
$("#btnSave").on("click", function () {
console.log("Button is clicked");
});
</script>
</head>
<body>
<button id="btnSave">Save</button>
</body>
</html>Open the console and you will see:
Buttons found: 0Now click the button and nothing is logged. There is no error either, which makes this bug confusing for beginners.
The browser reads the page from top to bottom. When it runs the script in the <head>, the <button> further down has not been parsed, so it is not in the DOM yet. The selector $(“#btnSave”) returns an empty jQuery object, and calling .on(“click”, …) on an empty object does nothing. The code does run, but it attaches the click handler to zero elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
console.log("Buttons found: " + $("#btnSave").length);
$("#btnSave").on("click", function () {
console.log("Button is clicked");
});
});
</script>
</head>
<body>
<button id="btnSave">Save</button>
</body>
</html>The console now shows:
Buttons found: 1Clicking the button logs Button is clicked. The only change is the $(document).ready() wrapper. It delays the code until the DOM is complete, so the button exists when the selector runs.
Tip: If a jQuery event is not firing, check .length on your selector first. If it is 0, jQuery did not find the element, and timing is one of the most common causes.
Many tutorials say you must always put all your jQuery code inside $(document).ready(). That is a good habit, but it is not a strict rule. What matters is that your code runs after the elements it uses exist in the DOM. There are a few ways to guarantee that.
If your script is the last thing before </body>, the browser has already parsed every element above it, so the DOM is ready when your code runs.
<body>
<button id="btnSave">Save</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// Safe without document ready: the button is already in the DOM
$("#btnSave").on("click", function () {
console.log("Button is clicked");
});
</script>
</body>A script with the defer attribute is downloaded while the HTML is being parsed, but it only runs after parsing is finished. Deferred scripts run in the order they appear, so jQuery must also be deferred and listed before your own file.
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" defer></script>
<script src="/js/site.js" defer></script>
</head>Note that defer only works on external scripts that have a src. It has no effect on inline <script> blocks.
Yes, in most cases. It costs almost nothing, and it keeps your code safe if someone later moves the script tag, for example from the bottom of the page to the <head>. A good rule is:
This is a common misunderstanding. $(document).ready() only guarantees that the elements already in the HTML exist. It does not help with elements that are created afterwards, for example through AJAX, .append() or a template.
$(document).ready(function () {
// Attached only to buttons that exist right now
$(".btn-delete").on("click", function () {
console.log("Deleted");
});
// A button added later does NOT get the handler above
$("#list").append('<button class="btn-delete">Delete</button>');
});To handle clicks on elements that do not exist yet, use event delegation. Attach the handler to a parent that already exists and give .on() a selector for the child:
$(document).ready(function () {
// Works for current and future .btn-delete buttons
$("#list").on("click", ".btn-delete", function () {
console.log("Deleted");
});
$("#list").append('<button class="btn-delete">Delete</button>');
});Here the handler is bound to #list, which exists at DOM ready. When a click happens on a .btn-delete inside it, jQuery runs the function, even if that button was added later.
These are the problems beginners run into most often. Each one comes with the error you will see in the browser console (press F12 to open it) and the fix.
<script>
$(document).ready(function () { // ReferenceError: $ is not defined
console.log("Ready");
});
</script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>The browser runs scripts in the order it meets them. Here your code runs before jQuery exists, so the browser does not know what $ is. Always load the jQuery library first:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
console.log("Ready");
});
</script>The same error appears if the jQuery file fails to download (a wrong path, a blocked CDN or no internet connection). Check the Network tab in the developer tools to confirm the file loaded.
Be careful with defer too. A deferred jQuery file runs only after the page is parsed, so an inline script that uses $ will run too early. Either defer both scripts as external files, or do not defer jQuery.
<script src="/js/jquery.datepicker.js"></script> <!-- plugin first: wrong -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#dob").datepicker(); // TypeError: $(...).datepicker is not a function
});
</script>A jQuery plugin adds its methods to jQuery when it loads. If jQuery is not there yet, the plugin cannot register itself. The correct order is: jQuery, then plugins, then your own code.
Adding the jQuery file a second time, often because a layout page and a view page both include it, replaces the first copy. Any plugins that were attached to the first copy are lost, and you get errors such as is not a function even though the plugin file is on the page. Include jQuery only once.
<button onclick="saveData()">Save</button>
<script>
$(document).ready(function () {
function saveData() {
console.log("Saved");
}
});
</script>Clicking the button gives Uncaught ReferenceError: saveData is not defined. The function is declared inside the ready callback, so it exists only inside that callback. The inline onclick looks for it in the global scope and cannot find it.
There are two fixes. The better one is to bind the event in jQuery and drop the inline attribute:
<button id="btnSave">Save</button>
<script>
$(document).ready(function () {
$("#btnSave").on("click", function () {
console.log("Saved");
});
});
</script>The other is to declare the function outside the ready block so that it is global. This works, but it is less tidy.
Some libraries, such as Prototype, also use $. When they are loaded together, $ may not mean jQuery any more. Use the full name jQuery instead, and pass $ into the callback so you can still write short code inside it:
jQuery(document).ready(function ($) {
// Inside this function, $ always means jQuery
$("#btnSave").on("click", function () {
console.log("Saved");
});
});If you need to give the $ symbol back to the other library completely, call jQuery.noConflict() after loading jQuery.
$(document).ready(function () {
$(".btnSave").on("click", function () { // the element has id="btnSave", not a class
console.log("Saved");
});
});jQuery does not complain when a selector matches nothing. The handler is simply attached to zero elements. The usual causes are using . where you needed # (or the reverse), a typo in the id, or a different spelling or case. As shown earlier in this tutorial, check the length of the result first:
console.log($("#btnSave").length); // 0 means jQuery found nothingThe link to download the source codes is given below: