Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 56 ยท Getting Started

The Document Ready Event

Learn how jQuery's document ready handler works, how it differs from DOMContentLoaded and window load, and how jQuery 3 runs ready handlers asynchronously.

In the previous lesson you saw that jQuery code needs the elements to exist before it can use them. The document ready handler is jQuery's answer: it waits until the browser has built the DOM, and only then runs your code. It is the first thing you will see in almost every jQuery file ever written.

This lesson explains the syntax, shows what "ready" really means compared with the load event, and describes a few details of jQuery 3, such as why ready handlers always run asynchronously.

The ready handler

There are three common ways to write it. They all do the same job:

JavaScript
$(document).ready(function () {
  // the DOM is ready
});

$(function () {
  // exactly the same, shorter
});

$(() => {
  // arrow function version
});

The short form $(function) is the one you will meet most often. Passing a function to $() means "run this when the document is ready". Inside the handler you can select any element on the page, because the HTML has been fully parsed.

Run code once the DOM is ready

The script comes before the list, yet it works. The callback is postponed until the browser has parsed the whole page. Remove the $(function () { ... }) wrapper and the count will stay as a question mark.

What "ready" means

Browsers fire two important events while a page loads:

Event Fires when jQuery spelling
DOMContentLoaded The HTML is parsed and the DOM tree is built. Scripts and deferred scripts have run, but images and other resources may still be loading. $(function(){})
load Everything has finished, including images, stylesheets and frames. $(window).on("load", fn)

jQuery's ready event is based on DOMContentLoaded. That is usually what you want, because you can start working with the structure of the page without waiting for a large photo to download.

You need load only when your code depends on the finished resources, for example measuring an image's natural size or reading the dimensions of a laid-out page that depends on loaded fonts.

Ready versus load

In a normal browser the ready line appears first, because the DOM is built while the image is still being fetched. If the image were already cached the two could come close together, which is exactly why the two events are separate: ready means "the structure is there", load means "the resources are there".

Placing scripts instead of waiting

Waiting for ready is not the only way to be safe. If your scripts sit at the very end of <body>, just before </body>, every element above them has already been parsed, so no wrapper is needed:

HTML
<body>
  <button id="save">Save</button>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
  <script>
    $("#save").on("click", saveForm);  // #save is above, so it exists
  </script>
</body>

A script in the <head> can use the defer attribute, which downloads the file in parallel but runs it only after the document is parsed:

HTML
<script defer src="/js/app.js"></script>

Deferred scripts run in order, just before DOMContentLoaded. Note that defer works only on external files; it has no effect on inline scripts. Even when you use one of these placements, many developers still wrap their code in $(function(){ ... }). It costs almost nothing, and it keeps the code safe if someone later moves the script tag.

Several ready handlers

You can register as many ready handlers as you like, in as many files as you like. They run in the order they were added:

Handlers run in order

The plain call step("0: ...") appears first in the list, even though it is written last. That is the asynchronous behavior of jQuery 3, explained next.

jQuery 3: ready handlers are always asynchronous

In jQuery 1.x and 2.x, if you called $(fn) after the document was already ready, fn ran immediately, in the middle of your current code. If the document was not ready yet, it ran later. The same code could run in two different orders depending on timing, which is a classic source of subtle bugs.

jQuery 3 fixed this: a ready handler always runs asynchronously, after the current script finishes, whether or not the DOM was already ready. Your code now behaves the same way every time.

jQuery 3 also made errors safer. If one ready handler throws an exception, the error is reported to the console, but the remaining handlers still run. In older versions, one broken handler stopped all the later ones.

Several older spellings were removed or deprecated in jQuery 3, and you may see them in legacy code:

JavaScript
$(document).on("ready", fn);   // removed in jQuery 3: never fires
$("document").ready(fn);       // deprecated form
$().ready(fn);                 // deprecated form

When you modernize old code, convert all of them to $(function () { ... }). The What Changed in jQuery 3 lesson lists more of these differences.

Where does your code run?

Parsing The browser reads the HTML top to bottom.
DOM ready Tree built. jQuery ready handlers fire.
Load Images and styles finish. Window load fires.

Ready comes first, load comes last.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement is equivalent to $(document).ready(handler)?

    Passing a function straight to $() is the shorthand for the document ready handler.
  2. 2. Your code measures the natural width of a large photo. Which event should it wait for?

    Document ready fires when the DOM is built, often before images finish. The window load event waits for all resources.
  3. 3. In jQuery 3, what happens if you call $(fn) after the document is already ready?

    jQuery 3 always calls ready handlers asynchronously so the order of execution is predictable.
  4. 4. What is true about the defer attribute?

    defer applies to external scripts only. They download in parallel and run in order once parsing finishes, before DOMContentLoaded.

Summary

  • $(function () { ... }) runs your code once the DOM is built; it is short for $(document).ready(...).
  • Ready is based on DOMContentLoaded and fires before load; use $(window).on("load", ...) only when you need images and other resources.
  • Placing scripts at the end of the body, or using defer, are alternatives, and combining them with ready is harmless.
  • You can register many ready handlers; they run in the order they were added.
  • In jQuery 3, ready handlers are always asynchronous, and one failing handler no longer stops the others.

Next, let's find out what $() actually returns, in The jQuery Object.