What is the Equivalent of $(document).ready in JavaScript

What is the Equivalent of $(document).ready in JavaScript

You can use $(document).ready() to make sure the DOM is fully loaded using jQuery. You should make sure the DOM is ready before running your script. With vanilla JavaScript (plain JavaScript without libraries), there are several ways to do the same thing. The methods like defer Attribute in <script> Tag, window.onload, and setTimeout() are used to call the function when the page is ready. We will discuss these methods in this blog in detail.

Table of Contents:

Why wait for the DOM to be ready?

The browser loads HTML in sequence. If the JavaScript runs before the elements are available, that results in an error. To prevent this issue, we ensure the JavaScript runs only after the DOM/page gets fully loaded. 

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

There are many methods to call a function when the page/DOM is ready. Let us discuss these methods below.

Method 1: Using the DOMContentLoaded Event

You can use the DOMContentLoaded Event to check the DOM’s loading status. This event checks the loading status only if the HTML is completely loaded and processed, even if images or other external resources are still loading.

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 triggers when the document’s structure is ready. You can attach an event listener to run a function when this happens. The JavaScript then updates the text inside the <h1> element once the DOM is fully loaded.

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

The attribute can be used in the <script> tag. This attribute waits until the DOM is completely loaded before the execution of 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: You can use this code to make sure the script only runs after the DOM is ready. This is done by ared attribute. You load the script externally, so you don’t need to put it inside an event listener in this method. 

Note: DOMContentLoaded is just for demonstration purposes because guarantees that the script runs after the DOM is loaded.

Method 3: Using a window.onload

The event used here waits for the entire page to get loaded, which also includes the image. After the loading, the script gets executed.

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 = "Page is fully loaded!";
        };
    </script>
</body>
</html>

Output:

Using a window.onload

Explanation: You can use the window.onload event in this code to make sure the script is executed only after the page is ready. This event can be effective when you need to manipulate the elements that depend on external resources.

Method 4: Using setTimeout() as a Fallback

You can use setTimeout() if you can’t change where the script is placed. The functions are used as a fallback to delay execution until rendering begins.

Example:

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

Output:

Using setTimeout as a Fallback

Explanation: The code contains a setTimeout() function for executing scripts over 100 milliseconds and making sure the DOM is ready. 

Best Practices

  • You can prefer the DOMContentLoaded Event since it is a more efficient method to make the DOM ready before the execution of the script.
  • The attribute can be used to add the external script to make the HTML document look cleaner.
  • You can use the window.onload when working with images that must be fully loaded before scripting.

Conclusion

The methods like  DOMContentLoaded event, Attribute in <script> Tag, window.onload, and setTimeout() function are used for the page/DOM to get fully loaded before executing the JavaScript. You can prevent errors like cannot read properties of null by using these methods.

FAQs

Q1. When should I use the DOMContentLoaded event?

The DOMContentLoaded event can be used when you want to execute the script after the HTML document is fully loaded without waiting for images or other resources.

Q2. Can I use window.onload instead of DOMContentLoaded?

Yes, you can use the window.onload instead of using DOMContentLoaded but, windows.onload waits for the entire page to load, including images and other external resources, and this can cause more delay as compared to DOMContentLoaded.

Q3. Do I need a fallback for older browsers?

DOMContentLoaded is widely supported by modern browsers. However, for browsers (like IE8 and earlier), you might need additional checks or polyfills since they are old.

Q4. Does the defer attribute work as an alternative?

Yes, the defer attribute ensures that the script runs after the DOM is ready, making it a simple and effective alternative.

Q5. What’s the difference between DOMContentLoaded and load events?

The DOMContentLoaded event starts as soon as the HTML is loaded and parsed, but the load event waits for all things, like images and stylesheets, to load as well.

Full Stack Development