Home  >  Article  >  Web Front-end  >  How to Determine DOM Readiness without Frameworks?

How to Determine DOM Readiness without Frameworks?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-20 10:27:02542browse

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>

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>

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>

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>

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!

Statement:
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