Home > Web Front-end > JS Tutorial > body text

How to Determine DOM Readiness without Frameworks?

Patricia Arquette
Release: 2024-10-20 10:27:02
Original
534 people have browsed it

How to Determine DOM Readiness without Frameworks?

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:

<code class="js">if (document.readyState === 'complete') {
  // DOM is ready
}</code>
Copy after login

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:

<code class="js">function fireOnReady() {
  // ...
}
if (document.readyState === 'complete') {
  fireOnReady();
} else {
  document.addEventListener("DOMContentLoaded", fireOnReady);
}</code>
Copy after login

Leveraging jQuery's Undocumented isReady Property

Although undocumented, jQuery exposes an isReady property that internally indicates the DOM ready state:

<code class="js">if ($.isReady) {
  // DOM is ready
} else {
  // DOM is not yet ready
}</code>
Copy after login

Lightweight DOM Ready Snippet

Inspired by Dustin Diaz's snippet, you can create a mini DOM ready listener as follows:

<code class="js">if (!/in/.test(document.readyState)) {
  // Document is ready
} else {
  // Document is not ready
}</code>
Copy after login

This check leverages the fact that the readyState value contains "in" in earlier loading states, making it a reliable indicator of DOM readiness.

The above is the detailed content of How to Determine DOM Readiness without Frameworks?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!