How to check if a document is ready in JavaScript?

In JavaScript, you can check if the DOM is fully loaded using document.readyState or event listeners. This is crucial for ensuring your scripts run after the HTML structure is ready.

Understanding document.readyState

The document.readyState property has three possible values:

  • "loading" - The document is still loading
  • "interactive" - The document has loaded but resources like images may still be loading
  • "complete" - The document and all resources have finished loading

Method 1: Using document.readyState

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Ready Check</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: blueviolet;
            margin: 20px 0;
        }
        .btn {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Check if Document is Ready</h1>
    <div class="result"></div>
    <button class="btn">Check Document State</button>
    <p>Click the button to see the current document state</p>

    <script>
        let resultDiv = document.querySelector(".result");
        let checkBtn = document.querySelector(".btn");
        
        // Display initial state
        resultDiv.innerHTML = "Initial state: " + document.readyState;
        
        checkBtn.addEventListener("click", () => {
            if (document.readyState === "complete") {
                resultDiv.innerHTML = "? Document is fully loaded and ready!";
            } else if (document.readyState === "interactive") {
                resultDiv.innerHTML = "? DOM is ready, but resources may still be loading";
            } else {
                resultDiv.innerHTML = "? Document is still loading";
            }
        });
    </script>
</body>
</html>

Method 2: Using DOMContentLoaded Event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOMContentLoaded Example</title>
</head>
<body>
    <div id="status">Loading...</div>
    
    <script>
        // Method 1: Check if already loaded
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", function() {
                document.getElementById("status").innerHTML = "DOM is ready!";
            });
        } else {
            document.getElementById("status").innerHTML = "DOM was already ready!";
        }
        
        // Method 2: Always safe approach
        function onDOMReady(callback) {
            if (document.readyState !== "loading") {
                callback();
            } else {
                document.addEventListener("DOMContentLoaded", callback);
            }
        }
        
        onDOMReady(function() {
            console.log("DOM is ready to manipulate!");
        });
    </script>
</body>
</html>

Comparison of Methods

Method When to Use Pros Cons
document.readyState Check current state Immediate status check Requires manual polling
DOMContentLoaded Wait for DOM ready Event-driven, efficient Won't fire if DOM already loaded
Combined approach Production code Handles all scenarios Slightly more complex

Practical Use Case

<script>
// Safe function to ensure DOM is ready
function whenReady(callback) {
    if (document.readyState !== "loading") {
        // DOM is already ready
        callback();
    } else {
        // Wait for DOM to be ready
        document.addEventListener("DOMContentLoaded", callback);
    }
}

// Usage
whenReady(function() {
    // Your code here - DOM is guaranteed to be ready
    document.getElementById("myElement").style.color = "blue";
    console.log("DOM manipulation is safe now!");
});
</script>

Conclusion

Use DOMContentLoaded event for most cases where you need to wait for the DOM. For immediate status checks, use document.readyState. The combined approach ensures your code works regardless of when the script executes.

Updated on: 2026-03-15T23:18:59+05:30

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements