Understanding DOM Readiness without Frameworks
When developing web applications, determining when the Document Object Model (DOM) is ready for manipulation is crucial. While frameworks like jQuery offer readyState listeners, this article explores alternative approaches to detecting DOM readiness.
Direct Access to DOM State
Instead of relying on frameworks, you can directly check the document'sreadyState property:
if (document.readyState === 'complete') {
// DOM is ready
}
However, this approach is unreliable across browsers, as some may not provide an accurate readyState value.
Event-Based DOM Ready Check
A more cross-browser approach is to listen for the DOMContentLoaded event, which fires when the DOM is ready for manipulation:
function fireOnReady() {
// ...
}
if (document.readyState === 'complete') {
fireOnReady();
} else {
document.addEventListener("DOMContentLoaded", fireOnReady);
}
Leveraging jQuery's Undocumented isReady Property
Although undocumented, jQuery exposes an isReady property that internally indicates the DOM ready state:
if ($.isReady) {
// DOM is ready
} else {
// DOM is not yet ready
}
Lightweight DOM Ready Snippet
Inspired by Dustin Diaz's snippet, you can create a mini DOM ready listener as follows:
if (!/in/.test(document.readyState)) {
// Document is ready
} else {
// Document is not ready
}
This check leverages the fact that the readyState value contains "in" in earlier loading states, making it a reliable indicator of DOM readiness.
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