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

When Is the DOM Ready in JavaScript?

DDD
Release: 2024-10-20 12:59:02
Original
707 people have browsed it

When Is the DOM Ready in JavaScript?

Understanding DOM Readiness in JavaScript

When working with dynamic web pages, understanding DOM readiness is crucial for executing tasks at the appropriate time. While frameworks like Prototype and jQuery provide convenient mechanisms to attach functions to the window.onload event, there are situations where a more direct approach is desired.

Querying DOM Readiness

If you seek an alternative to using frameworks, there are a few methods you can explore:

1. jQuery's Undocumented "isReady" Property:

Despite being undocumented, jQuery maintains an internal property called isReady. When accessible, it indicates whether the DOM ready event has fired:

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

While this approach has been stable across multiple jQuery versions, it remains undocumented and should be used with caution.

2. Document ReadyState:

The document object offers a readyState property that reflects the loading status of the page:

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

By listening for the DOMContentLoaded event, you can execute code when the page is fully loaded.

3. Custom DOM Ready Check:

For scenarios where browser compatibility is paramount, you can create a custom DOM ready check inspired by Dustin Diaz's snippet:

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

This approach leverages the fact that the loading states "loading" and "interactive" contain the string "in" in their readyState property. As a result, if "in" is found in the readyState, the document is not yet ready.

The above is the detailed content of When Is the DOM Ready in JavaScript?. 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
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!