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!