Episode 17 of 24

Document Ready vs Window Load

Understand the difference between document ready and window load events in jQuery.

jQuery provides two key events for running code when the page loads. Understanding the difference is important.

$(document).ready()

Fires when the DOM is fully parsed — images and stylesheets may still be loading:

$(document).ready(function() {
    console.log("DOM is ready!");
    // Safe to manipulate HTML elements
    $("h1").text("Page loaded!");
});

// Shorthand (most common)
$(function() {
    console.log("DOM is ready!");
});

$(window).on("load")

Fires when everything has loaded — HTML, CSS, images, iframes:

$(window).on("load", function() {
    console.log("Everything is loaded!");
    // Safe to work with image dimensions, etc.
    let imgWidth = $("img").width();
    console.log("Image width:", imgWidth);
});

The Difference

  • $(document).ready() — fires first, as soon as HTML is parsed
  • $(window).on("load") — fires later, after all assets are loaded
$(function() {
    console.log("1. DOM ready (fires first)");
});

$(window).on("load", function() {
    console.log("2. Window loaded (fires second)");
});

When to Use Which

  • $(document).ready() — for most jQuery code (DOM manipulation, event binding)
  • $(window).on("load") — when you need image dimensions, or all assets must be available

Multiple Ready Handlers

// You can have multiple — they all run
$(function() {
    console.log("First ready handler");
});

$(function() {
    console.log("Second ready handler");
});
// Both will execute!