Home  >  Article  >  Web Front-end  >  Is There an Alternative Way to Check for DOM Readiness in Javascript Without Using Frameworks?

Is There an Alternative Way to Check for DOM Readiness in Javascript Without Using Frameworks?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 10:23:30998browse

Is There an Alternative Way to Check for DOM Readiness in Javascript Without Using Frameworks?

Determining Document Readiness in Javascript

Question:

Is there an alternative way to check for DOM readiness in Javascript, without relying on frameworks like prototype or jQuery?

Answer:

Option 1: DOMContentLoaded Event

The DOMContentLoaded event fires when the initial HTML document has been parsed and the DOM is ready for manipulation. To use this event:

function fireOnReady() { /* ... */ }
if (document.readyState === 'complete') {
    fireOnReady();
} else {
    document.addEventListener("DOMContentLoaded", fireOnReady);
}

Note that this event only fires once when the page loads.

Option 2: jQuery's isReady Property (Undocumented)

jQuery has an undocumented property called isReady that can be used to check for DOM readiness:

if($.isReady) {
    // DOM is ready
} else {
    // DOM is not yet ready
}

While this property is reliable, it is not officially documented and may be removed in future jQuery versions.

Option 3: Custom ReadyState Check

Inspired by Dustin Diaz, you can create a custom DOM ready snippet that checks the document.readyState property:

if( !/in/.test(document.readyState) ) {
    // document is ready
} else {
    // document is NOT ready
}

This works because the document.readyState property goes through three loading states: "loading", "interactive", and "complete". "Loading" and "interactive" both contain the text "in", indicating that the DOM is not yet ready.

The above is the detailed content of Is There an Alternative Way to Check for DOM Readiness in Javascript Without Using 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