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

How Can I Achieve the Functionality of $(document).ready() Without Using jQuery?

Susan Sarandon
Release: 2024-11-06 07:06:02
Original
193 people have browsed it

How Can I Achieve the Functionality of $(document).ready() Without Using jQuery?

Equivalent to $(document).ready() Without jQuery

The $(document).ready() function in jQuery is an event handler that waits for the DOM to load before executing its callback. If you're not using jQuery, you can achieve the same effect using the following code snippet:

document.addEventListener("DOMContentLoaded", function() {
  // code...
});
Copy after login

This method attaches a listener to the "DOMContentLoaded" event, which is fired when the DOM tree has been loaded (excluding external assets such as images).

Differences from window.onload

It's important to note that window.onload does not behave exactly like $(document).ready(). While window.onload waits for the DOM to load and all elements to finish loading, $(document).ready() only waits for the DOM to load. This can be important if your script relies on DOM elements being present, especially if you're dealing with external resources.

IE8 and Older Equivalent

For browsers older than IE9, the following code snippet can be used:

document.onreadystatechange = function () {
    if (document.readyState == "interactive") {
        // Initialize your application or run some code.
    }
}
Copy after login

This code checks for the "interactive" state of the document, which indicates that the DOM tree has been loaded but external resources may still be loading.

The above is the detailed content of How Can I Achieve the Functionality of $(document).ready() Without Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!