You're absolutely right to want 100% certainty that your code runs only after the DOM is fully ready, and without any race conditions. Let's dig into bulletproof, battle-tested techniques that guarantee execution when the DOM is ready — even in async scripts.
✅ The Problem Restated
When using an async script:
- It can execute at any time during page load.
- If you check
document.readyState and then attach a listener, there's a tiny but real race condition where DOMContentLoaded could fire between those two steps.
- This means your code might never run.
So we need a guaranteed way to run code only once the DOM is ready — whether it fires before or after your script starts executing.
🔐 100% Reliable Solution: Use a Double-Fire-Proof Wrapper
Here’s a robust, race-condition-free pattern that ensures your code runs exactly once, either immediately (if DOM is already ready) or when the event fires:
✅ Final Bulletproof Pattern
(function domReady(handler) {
if (document.readyState === "interactive" || document.readyState === "complete") {
// Already past loading phase — just run handler now
handler();
} else {
// Not ready yet — listen for DOMContentLoaded
document.addEventListener("DOMContentLoaded", handler);
}
})(function onDomReady() {
// Your actual code here
console.log('DOM is READY. Safely manipulate the DOM.');
});
🧠 Why This Works
- We immediately invoke a function expression (
!function(){} or (function(){})()) that checks the state.
- If the DOM is already interactive/complete, we call the handler right away.
- Otherwise, we set up the listener before any other logic, which avoids the race condition.
- Even if the event has already fired by the time this runs, the check catches it.
This approach is used internally by many libraries like jQuery and modern frameworks to safely detect DOM readiness.
🧪 Test Case to Confirm It Works
Let’s simulate a worst-case scenario where the DOM loads just as the script is being parsed:
✅ This method will still catch it because:
- Listener is attached after checking the readyState,
- But the check happens before anything else, so no race window.
If DOMContentLoaded had already fired, we call the handler directly.
📦 Optional: Wrap It in a Reusable Utility
If you're going to use this multiple times, make a helper:
function onDomReady(callback) {
if (document.readyState === "interactive" || document.readyState === "complete") {
callback();
} else {
document.addEventListener("DOMContentLoaded", function onReady() {
document.removeEventListener("DOMContentLoaded", onReady);
callback();
});
}
}
Then use it anywhere:
onDomReady(() => {
console.log('Safe and guaranteed DOM ready!');
});
💡 This version also removes the listener after firing once — just to be extra clean.
🛠️ Alternative: Use defer Instead of async
If your use case allows it, use <script defer> instead of <script async>.
Why defer Is Safer
- Scripts with
defer are:
- Downloaded asynchronously (non-blocking)
- Executed after the document has been completely parsed
- So you don’t even need to wait for
DOMContentLoaded — it’s guaranteed to run after the DOM is ready.
Example:
<script src="your-script.js" defer></script>
In your-script.js:
// No need for DOMContentLoaded — DOM is guaranteed to be ready!
console.log(document.body); // safe to access
🧱 Summary Table
| Strategy | Race Condition? | Guaranteed Execution? | Notes |
|---|
Check readyState, then add listener | ❌ Yes | ❌ No | Risky |
| Add listener first, then check state | ✅ No | ✅ Yes | Solid solution |
| Self-invoking wrapper (check first) | ✅ No | ✅ Yes | Most reliable |
Use defer attribute | ✅ No | ✅ Yes | Simpler than JS logic |
| MutationObserver / Polling | ✅ No | ✅ Yes | Overkill, not needed |
🧩 Bonus: For Advanced Users – Hybrid Fallback
If you really want to go overboard (e.g., for critical production systems), you can combine:
- DOMContentLoaded listener
- ReadyState check
- MutationObserver fallback
- Timeout guard
But for almost all use cases, the self-invoking wrapper above is more than enough.
✅ Final Recommendation
Use this self-invoking wrapper:
(function domReady(handler) {
if (document.readyState !== "loading") {
handler();
} else {
document.addEventListener("DOMContentLoaded", handler);
}
})(function onDomReady() {
// Safe DOM manipulation here
console.log('DOM is ready!');
});
Or better yet, switch to:
<script src="your-script.js" defer></script>
And avoid all the JavaScript complexity altogether.
Let me know if you'd like a version compatible with older browsers (like IE11), or integrated with a module bundler like Webpack or Vite!