Document.isReady: A Native Solution for DOM Ready Detection
Dependence on frameworks like Prototype and jQuery for managing window.onload events may not always be desirable. This article explores alternative methods for determining DOM readiness, particularly through the use of document.isReady.
Querying Document.isReady
For modern browsers with stable event APIs, the DOMContentLoaded event provides a robust method for handling DOM ready events. Implementations like the following offer a simple and efficient solution:
function fireOnReady() { /* ... */ }
if (document.readyState === 'complete') {
fireOnReady();
} else {
document.addEventListener("DOMContentLoaded", fireOnReady);
}
jQuery's $.isReady Property
jQuery offers an undocumented property, $.isReady, which reflects the DOM ready state internally. Utilizing this property allows for concise checks:
if($.isReady) {
// DOM is ready
} else {
// DOM is not yet ready
}
It is crucial to note that this property remains undocumented and its availability in future jQuery versions cannot be guaranteed. Use it with caution and be prepared for potential changes upon upgrades.
A Custom DOM Ready Snippet
For wider browser compatibility, a custom DOM ready snippet can be employed. Inspired by Dustin Diaz's approach, it checks the document.readyState using a regular expression:
if( !/in/.test(document.readyState) ) {
// document is ready
} else {
// document is NOT ready
}
This method relies on the fact that the "in" substring is present in the "loading" and "interactive" ready states but not in the "complete" state.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3