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
- What is event delegation, and why is it useful?
- What is the difference between .html() and .text(), and why does it matter for security?
- How do you make AJAX requests with jQuery?
- What is the difference between .attr() and .prop()?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What are jQuery Deferreds, and how do you wait for several requests?
- What is jQuery, and is it still relevant today?