Home > Web Front-end > JS Tutorial > How to Detect DOM Ready Event in Javascript Without Frameworks?

How to Detect DOM Ready Event in Javascript Without Frameworks?

Patricia Arquette
Release: 2024-10-20 13:04:02
Original
384 people have browsed it

How to Detect DOM Ready Event in Javascript Without Frameworks?

Javascript DOM Ready Event Detection Without Frameworks

In Javascript, developers often rely on frameworks like Prototype or jQuery to attach functions to the window.onload event to perform certain tasks. However, there are other ways to achieve this without using these frameworks.

The document object in Javascript has a readyState property that indicates the loading stage of the page, similar to the readyState property of AJAX requests. The readyState property can have the following values:

  • loading - The page is still loading and DOM elements are not yet available.
  • interactive - The page is loaded and DOM elements are mostly ready for interaction, but images and other resources may still be loading.
  • complete - The page is fully loaded and all DOM elements are available.

To detect when the DOM is ready, you can use the following code:

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

This code checks if the page is already fully loaded (readyState is 'complete') and executes the fireOnReady function immediately. Otherwise, it attaches a callback to the DOMContentLoaded event, which fires when the DOM is ready, and executes the fireOnReady function.

Another option is to use jQuery's undocumented isReady property:

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

However, this property is not documented and may be removed in future versions of jQuery.

Ultimately, listening for the DOMContentLoaded event is the most reliable way to detect when the DOM is ready in modern browsers.

The above is the detailed content of How to Detect DOM Ready Event in Javascript 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