Home  >  Article  >  Web Front-end  >  How Can I Achieve the Functionality of $(document).ready() Without Using jQuery?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-06 07:06:02194browse

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...
});

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.
    }
}

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!

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