Home > Web Front-end > JS Tutorial > How to Achieve the Functionality of $(document).ready() Without jQuery?

How to Achieve the Functionality of $(document).ready() Without jQuery?

DDD
Release: 2024-11-05 01:33:02
Original
460 people have browsed it

How to Achieve the Functionality of $(document).ready() Without jQuery?

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.
    }
}
Copy after login

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!

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