Home > Web Front-end > JS Tutorial > body text

How to Achieve $(document).ready() Functionality with Vanilla JavaScript?

DDD
Release: 2024-11-05 12:05:02
Original
919 people have browsed it

How to Achieve $(document).ready() Functionality with Vanilla JavaScript?

Non-jQuery Alternative to $(document).ready()

The industry-standard jQuery library provides the $(document).ready() method, which enables developers to execute code after the Document Object Model (DOM) has been fully loaded, ensuring that all elements are accessible and the page content is ready to be manipulated. However, what are the alternatives to this method when working with vanilla JavaScript?

Answer:

The non-jQuery equivalent of $(document).ready() is achieved through event listeners. The following code snippet demonstrates how to achieve this functionality:

<code class="javascript">document.addEventListener("DOMContentLoaded", function() {
    // code to be executed when the DOM is fully loaded
});</code>
Copy after login

This implementation accomplishes the same result as $(document).ready(), allowing developers to execute code only after the DOM is complete.

Additional Considerations:

While document.addEventListener("DOMContentLoaded") provides a solution to waiting for DOM readiness, it differs from window.onload in terms of its behavior. $(document).ready() only waits for the DOM to be complete, whereas window.onload waits for both the DOM and all external assets, including images and scripts.

Alternative for Older Browsers (IE8 and below):

For older browsers such as Internet Explorer 8 and below, the following alternative can be used:

<code class="javascript">document.onreadystatechange = function() {
    if (document.readyState === "interactive") {
        // code to be executed when the DOM is fully loaded
    }
};</code>
Copy after login

Keep in mind that there are alternative states besides "interactive." Consult the Mozilla Developer Network (MDN) documentation for additional information.

The above is the detailed content of How to Achieve $(document).ready() Functionality with Vanilla JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template