Deferred loading

This method ensures that the JavaScript code inside the script tag is run after all of the HTML content has been loaded and parsed by positioning the <script> tag immediately before the closing </body> element at the conclusion of the HTML body. The code will thereafter have access to all DOM elements in this manner.

Example: The code example below demonstrates how we can implement the second approach. This code shows how we can actually use this approach to mimic the functionality of the $(document).ready() without using the DOMContentLoaded event.

HTML
<!DOCTYPE html>
<html>

<body>
    <h1 style="color: green;">
        w3wiki
    </h1>

    <h3>
        $(document).ready 
        equivalent without jQuery
    </h3>

    <strong style="color: sienna; 
                   margin: 2rem;" id="myText">
        DOM not loaded yet...
    </strong>
    <br>

    <strong style="color: sienna; 
                   margin-left: 2rem;" id="myText2">
    </strong>

    <script>
        let text = document
            .getElementById("myText");
        let text2 = document
            .getElementById("myText2");
        text.textContent =
            "In this code same result is achieved using";
        text2.textContent =
            "Using the second aprroach!";
    </script>
</body>

</html>

Output:



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

The jQuery function “$(document).ready()” is important for developers aiming to ensure seamless execution of code within their web applications. By using this function, code is executed only after the Document Object Model (DOM) has been fully loaded, thus preventing any potential errors stemming from incomplete page rendering. “$(document).ready()” facilitates the secure binding of events, interaction with DOM elements, and the execution of code dependent on the DOM. Its meticulous execution eliminates timing-related bugs, enhancing the reliability and stability of jQuery-powered applications.

When using jQuery is out of option and we want to get the same result without using jQuery, then we can use two approaches:

Table of Content

  • Approach 1: Using the “DOMContentLoaded” event
  • Approach 2: Deferred loading

Similar Reads

Approach 1: Using the “DOMContentLoaded” event

In this approach, we use the DOMContentLoaded event and in this, we can use it with both the window and the document. Without waiting for stylesheets, graphics, or subframes to fully load, the DOMContentLoaded event fires once the basic HTML content has loaded and been parsed. So, it gives us the same type of functionality that is provided by $(document).ready() with jQuery....

Approach 2: Deferred loading

This method ensures that the JavaScript code inside the script tag is run after all of the HTML content has been loaded and parsed by positioning the