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