Why jQuery’s ready Beats window.onload: Understanding DOM Ready Across Browsers
This article explains how jQuery’s ready method works, why it executes earlier than window.onload, and details the cross‑browser mechanisms—including DOMContentLoaded, document.readyState checks, and the doScroll technique—that ensure code runs as soon as the DOM is ready.
When using jQuery, the ready method is extremely common; developers typically write $(document).ready(function(){ ... }) or the shorthand $(function(){ ... }).
Why not use window.onload ? The window.onload event fires only after the entire page—including all images and sub‑resources—has finished loading. On pages with many images, users may start interacting with the page before the onload event fires, making it unsuitable for many interactive scripts.
What ready does is execute as soon as the DOM structure is fully built, without waiting for external resources. This provides a faster, more responsive experience.
How ready is implemented varies by browser:
Standard browsers
Modern browsers support the DOMContentLoaded event, which is triggered immediately after the HTML document has been parsed and the DOM tree is complete.
Non‑standard browsers
jQuery uses two fallback strategies:
If the browser provides the document.onreadystatechange event, jQuery checks for document.readyState === "complete". When this condition is met, the DOM is considered loaded. However, this event can be unreliable when images are present, as it may fire after onload.
For older IE versions, jQuery employs the doScroll technique. In IE, calling document.documentElement.doScroll('left') before the DOM is ready throws an exception. jQuery repeatedly attempts this call inside a try‑catch loop; when no exception occurs, it concludes that the DOM is ready.
Thus, by detecting the absence of an exception from doScroll, jQuery can reliably determine that the DOM has finished loading even in legacy browsers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
