The jQuery document ready function ensures that your JavaScript code runs only after the HTML document is fully loaded and ready to be manipulated.
It is important to understand the difference between $(document).ready() and window.onload.
| Feature | $(document).ready() | window.onload |
|---|---|---|
| Trigger Time | Runs as soon as HTML is parsed (Early). | Runs after HTML, Images, and Styles are loaded (Late). |
| Multiple Usage | Can differ multiple times; they run in order. | Only the last function assigned will run. |
| Use Case | Manipulating elements, binding events. | Calculations dependent on image dimensions. |
jQuery provides a built-in method to detect when the document is ready. This avoids errors caused by accessing elements before they exist.
// Standard document ready syntax
$(document).ready(function() {
console.log("DOM is fully loaded");
});
// Shorthand document ready syntax
$(function() {
$("#msg").text("jQuery is ready!");
});
When the page loads, jQuery waits until the DOM is ready, then updates the content of the selected element safely.
Live Playground
Below is a real working example. The status box detects when the DOM is ready automatically.
// 1. Wait for DOM Ready
$(document).ready(function() {
// 2. Update the visual indicator
$("#dom-status").text("DOM IS READY ✅").addClass("ready");
// 3. Bind the click event safely
$("#interactive-btn").click(function() {
$("#interactive-msg").slideDown(); // Animate visibility
$(this).text("Clicked!"); // Change button text
});
});
$(function(){...}) for cleaner code