jQuery interview question · Most asked

What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?

Summary

$(fn) (the recommended form of $(document).ready(fn)) runs when the DOM is parsed, like DOMContentLoaded, before images and stylesheets finish loading. window.onload (or $(window).on('load', fn)) waits for every resource, including images and iframes. jQuery's ready handler also runs immediately if the DOM is already ready when it is registered.

Longer Answer

Use the ready handler for setting up event handlers and DOM work; use the load event only when you need image dimensions or fully loaded resources. Scripts loaded at the end of <body> or with defer run after parsing anyway, so they often do not need a ready wrapper at all. Since jQuery 3, ready handlers run asynchronously, and the $(document).on('ready', fn) form was removed.

Code Example

$(function () {
  // DOM is ready: safe to query elements and bind events
  $("#save").on("click", save);
});

Key Points

  • $(fn) = DOM ready.
  • window load = all resources.
  • Ready runs immediately if already ready.
  • defer scripts may not need it.

More most-asked jQuery questions

← All jQuery questions