what-is-the-equivalent-of-$(document).ready-in-javascript

“`html

You can utilize $(document).ready() to ensure the DOM is completely loaded with jQuery. It is essential to confirm that the DOM is prepared before executing your script. In pure JavaScript (native JavaScript without libraries), there are multiple approaches to achieve the same objective. Techniques such as defer Attribute in <script> Tag, window.onload, and setTimeout() serve to invoke the function once the page is ready. This blog will elaborate on these techniques comprehensively.

Table of Contents:

Why should you wait for the DOM to be ready?

The browser processes HTML sequentially. If the JavaScript executes before the elements are available, it results in an error. To avert this problem, we ensure that the JavaScript executes only after the DOM/page is completely loaded.

Method to Invoke a Function When the page/DOM is Ready- Similar to jQuery’s $(document).ready()

There are various methods to invoke a function when the page/DOM is ready. Below, we will explore these methods.

Method 1: Utilizing the DOMContentLoaded Event

You can leverage the DOMContentLoaded Event to ascertain the loading state of the DOM. This event checks the loading status only after the HTML is fully loaded and processed, even if images and other external resources are still being loaded.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOMContentLoaded Example</title>
</head>
<body>
    <h1 id="message">Hello, World!</h1>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById("message").textContent = "DOM is fully loaded!";
        });
    </script>
</body>
</html>

Output:

Using the DOMContentLoaded Event

Explanation: The DOMContentLoaded event is triggered when the document structure is ready. You can add an event listener to execute a function at this moment. The JavaScript then modifies the text within the <h1> element as soon as the DOM is fully loaded.

Method 2: Using the Attribute in the <script> Tag

The attribute can be utilized in the <script> tag. This attribute ensures that the DOM is entirely loaded before executing the JavaScript.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Defer Attribute Example</title>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById("message").textContent = "DOM is fully loaded!";
        });
    </script>
</head>
<body>
    <h1 id="message">Hello, World!</h1>
</body>
</html>

Output:

Using the Attribute in the script Tag

Explanation: This code ensures that the script only executes after the DOM is ready. This is accomplished through the defer attribute. You can load the script externally, eliminating the need to embed it within an event listener in this approach.

Note: DOMContentLoaded is utilized for illustrative purposes as it guarantees that the script runs post DOM loading.

Method 3: Employing a window.onload

The event in question waits for the entire page to load, which also includes the images. After this loading process, the script executes.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Window Onload Example</title>
</head>
<body>
    <h1 id="message">Hello, World!</h1>
    <script>
        window.onload = function() {
            document.getElementById("message").textContent ``````html = "Page has completely loaded!";
        };
    </script>
</body>
</html>

Output:

Utilizing a window.onload

Explanation: The window.onload event is utilized in this script to ensure that the code runs only after the page is completely ready. This event is particularly useful when modifications of elements linked to external resources are necessary.

Method 4: Implementing setTimeout() as a Backup

If you are unable to alter the script placement, you can adopt setTimeout(). The functions serve as a backup to postpone execution until the rendering starts.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setTimeout Backup</title>
</head>
<body>
    <h1 id="message">Hello, World!</h1>
    <script>
        setTimeout(function() {
            document.getElementById("message").textContent = "DOM is now ready!";
        }, 100);
    </script>
</body>
</html>

Output:

Utilizing setTimeout as a Backup

Explanation: This code includes a setTimeout() function that delays script execution for 100 milliseconds to ensure the DOM is prepared.

Optimal Practices

  • Favor the DOMContentLoaded event as it efficiently prepares the DOM before the script execution.
  • The attribute can be utilized to embed external scripts, resulting in a cleaner HTML document.
  • Consider using window.onload when dealing with images that need full loading prior to scripting.

Wrap-Up

DOMContentLoaded event, the attribute in <script> tag, window.onload, and the setTimeout() function help ensure the page/DOM is fully loaded before executing JavaScript. These methods can prevent issues like being unable to read properties of null.

FAQs

Q1. When should I utilize the DOMContentLoaded event?

The DOMContentLoaded event should be used when you want your script to run post full HTML loading without waiting for images or other assets.

Q2. Is it possible to use window.onload as an alternative to DOMContentLoaded?

Indeed, you can opt for window.onload instead of DOMContentLoaded, but window.onload waits for the entire page to load, encompassing images and other external assets, which may lead to longer delays compared to DOMContentLoaded.

Q3. Is a fallback needed for older browsers?

While DOMContentLoaded is largely supported in modern browsers, you might need supplementary checks or polyfills for older browsers, such as IE8 and earlier.

Q4. Can the defer attribute act as an alternative?

Yes, the defer attribute guarantees that the script runs after the DOM has been prepared, making it a straightforward and effective alternative.

Q5. How do DOMContentLoaded and load events differ?

The DOMContentLoaded event triggers as soon as the HTML is parsed and loaded, while the load event waits for all elements, including images and stylesheets, to load too.

The post What is the Equivalent of $(document).ready in JavaScript appeared first on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This