Non-jQuery Equivalent of $(document).ready()**
The $(document).ready() function in jQuery is commonly used to execute code after the DOM is fully loaded. However, there are situations where using jQuery may not be desirable or available. In such cases, a non-jQuery equivalent is necessary.
Answer
The non-jQuery equivalent of $(document).ready() is document.addEventListener("DOMContentLoaded", function() { ... }). This function attaches an event listener to the DOMContentLoaded event, which is fired when the DOM tree is fully constructed. Code placed inside the event listener will be executed after the DOM is ready.
Differences from window.onload
Note that window.onload is not the same as $(document).ready(). window.onload only waits for all elements to be fully loaded, including external resources such as images and scripts. In contrast, $(document).ready() only waits for the DOM tree to be ready, which is generally faster.
IE8 and Older Support
For browsers older than IE8, an alternative to DOMContentLoaded is to use document.onreadystatechange with the following condition:
document.onreadystatechange = function () { if (document.readyState == "interactive") { // Initialize your application or run some code. } }
Other Options
Besides DOMContentLoaded, there are other event listeners that can be used to handle DOM loading. For more details, consult the Mozilla Developer Network (MDN) documentation.
The above is the detailed content of How to Achieve the Functionality of $(document).ready() Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!