
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Document Ready Equivalent in JavaScript
In this article, we will learn to achieve the same result as $(document).ready in JavaScript. In jQuery, $(document).ready() is a widely used function that ensures the DOM (Document Object Model) is fully loaded before executing JavaScript code.
Different approaches
The following are the approaches to achieve the same result as $(document).ready in JavaScript ?
Using document.readyState
In jQuery, if you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
$(document).ready(function() { alert("Document loaded successfully!"); });
The following are the steps to use the document.readyState ?
- The setInterval function checks every 300 milliseconds if document.readyState is complete.
- Once the condition is met, it clears the interval and executes the desired code.
if (document.readyState !== "complete") return;
Example
In JavaScript, to achieve the same result as $(document).ready, try the following code ?
<html> <body> <script> var loader = setInterval(function () { if (document.readyState !== "complete") return; clearInterval(loader); alert("Document loaded successfully!"); }, 300); </script> </body> </html>
Output
The following code uses document.readyState to alert a dialogue box ?
Using DOMContentLoaded Event
A more modern and efficient way to detect when the DOM is fully loaded is by using the DOMContentLoaded event. This event fires when the HTML is fully parsed, without waiting for stylesheets, images, or subframes to finish loading.
The following are the steps to use the DOMContentLoaded Event ?
- addEventListener listens for the DOMContentLoaded event.
- When the event triggers, the function runs the desired code.
document.addEventListener("DOMContentLoaded", function() { alert("Document loaded successfully!"); });
Example
Below is an example of using the DOMContentLoaded Event ?
<!DOCTYPE html> <html> <body> <script> document.addEventListener("DOMContentLoaded", function() { alert("Document loaded successfully!"); }); </script> </body> </html>
Output
The following code uses DOMContentLoaded to alert a dialogue box ?
Conclusion
Instead of using jQuery's $(document).ready(), modern JavaScript provides several efficient alternatives such as the DOMContentLoaded event, load event, and checking document.readyState. Among these, DOMContentLoaded is the best equivalent for most use cases as it ensures the script executes once the DOM is fully available without waiting for external resources.