DEV Community

Cover image for $(document).ready equivalent without jQuery
Navya Arora
Navya Arora

Posted on

$(document).ready equivalent without jQuery

In this article, we will see the $(document).ready method equivalent without using jQuery. In jQuery, the $(document).ready() method is used to execute JavaScript code as soon as the DOM (Document Object Model) is ready. It ensures that the DOM is fully loaded before executing any code that manipulates the DOM. This method only waits for the DOM to be loaded, without taking into account the loading of stylesheets, images, and iframes. This method specifies the function to execute when the DOM is fully loaded. There are a few ways by which similar functionality can be achieved without jQuery, i.e.,

  • By implementing the DOMContentLoaded event

  • By using the async/await function with the 'load' event

Approach 1:

We will use the DOMContentLoaded method to update the content of an HTML element as soon as it is ready. The DOMContentLoaded event fires when the initial HTML document has been completely parsed and loaded. It does not wait for stylesheets and images to finish loading.

This event gets executed once the basic HTML document is loaded and its parsing has taken place.

Some of the advantages of using the DOMContentLoaded event are:

  • It helps in improving user experience as it shows messages or content much faster.

  • It takes lesser time in loading the page.
    Syntax:

document.addEventListener("DOMContentLoaded", function(e) {
  console.log("GeeksforGeeks page has loaded!");
});
Enter fullscreen mode Exit fullscreen mode

Example:
In this example, we are displaying a heading using the

tags. The content of the heading will be displayed only when the HTML document has been completely loaded. This is ensured with the help of the DOMContentLoaded method.

<!DOCTYPE html>
<html>
  <head>
    <title>DOM Content Loaded Example</title>
    <script>

      document.addEventListener('DOMContentLoaded', () => {
        const greeting = document.querySelector('#greeting');
        greeting.textContent = 'GeeksforGeeks';
      });

    </script>
  </head>
  <body>
    <h1 style="color: green;" id="greeting"></h1>
    <h3>$(document).ready equivalent without jQuery</h3>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Output:

Output
The Javascript code inside the tags is executed when the initial DOMContentLoaded event is triggered. This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for external resources like images and stylesheets.

As a result, when the DOMContentLoaded event occurs, the

element with the id greeting will display the text GeeksforGeeks instead of being empty.

This demonstrates how to manipulate the content of HTML element using Javascript when the DOMContentLoaded event is triggered.

Approach 2:

We will use the readystatechange event, the readystatechange event is triggered when the ready state of the document changes. By checking if the document.readyState is set to "complete", you can determine when the DOM is ready. Here's an example:
Syntax:

document.onreadystatechange = function() {
  if (document.readyState === "complete") {
    console.log("Page is loaded completely!");
  }
};
Enter fullscreen mode Exit fullscreen mode

Example:
In this example, we are using the readystatechange event and checking the document.readyState property to determine when the DOM is ready.

The readystatechange event is triggered when the ready state of the document changes. The document.readyState property represents the current state of the document and can have different values throughout the loading process.

The document.readyState property can have the following values:

  • "loading": It means document is still loading.
  • "interactive": The DOM is loaded but some external resources are still loading.
  • "complete": The DOM is completely loaded. By using the document.onreadystatechange event and checking the document.readyState property, we can accurately detect when the DOM is ready and perform necessary actions or execute code accordingly in this example we are changing the background color of Click Me button to red and text to white on page load.
<!DOCTYPE html>
<html>

<head>
    <title>onreadystatechange Example</title>
</head>

<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>$(document).ready equivalent without jQuery</h3>
    <button id="myButton">Click me!</button>
</body>
<script>
    document.onreadystatechange = function () {
        if (document.readyState === "loading") {
            console.log('Page is loading');
        }
        if (document.readyState === "interactive") {
            console.log('DOM is ready');
        }
        if (document.readyState === "complete") {
            console.log('Page is fully loaded');
            const button = document.getElementById('myButton');
            button.style.backgroundColor = 'red';
            button.style.color = 'white';
        }
    };
</script>

</html>
Enter fullscreen mode Exit fullscreen mode

Output:

output

Supported Browsers:

  • Google Chrome 90.0+
  • Internet Explorer 9.0
  • Safari 4.0
  • Opera 10.5
  • Firefox 3.6

So here we used the $(document).ready method equivalent without using jQuery!!!

Connect me on Twitter:- Twitter 🤝🏻

Do check out my GitHub for amazing projects:- GitHub 🤝🏻

Connect me on LinkedIn:- Linkedin 🤝🏻

Top comments (7)

Collapse
 
adam_cyclones profile image
Adam Crockett

Woah blast from the past thanks for reminding me

Collapse
 
nyctonio profile image
Ritesh Kumar

Nice post

Collapse
 
aryan_shourie profile image
Aryan Dev Shourie

Informative!!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

A big pitfall with both of these approaches is that they will fail when the code ends up running after the document has already finished loading.

What makes this even worse is that this can lead to bugs that only show themselves occasionally but disappear depending on what files get retrieved from browser cache.

To avoid this one has to check the current load state of the document before or after attaching the corresponding event.

const do_something_when_loaded = () => {
   if (document.readyState == "loading")
      document.addEventListener("readystatechage", handler, { once: true })
   else
      do_something_fun()
}
do_something_when_loaded()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dimkiriakos profile image
dimkiriakos

ok! everyone know this but you still write more than jQuery command. next challenge is to do fade toggle with same amount of code without jQuery 😉

Collapse
 
navyaarora01 profile image
Navya Arora

for sure i will!

Collapse
 
garciaa profile image
Garciaa Maga

Thanks for the tip.