Question
JavaScript DOM Ready: Vanilla JS Equivalent of jQuery $(document).ready()
Question
How can I run JavaScript code as soon as the HTML document is ready, without using jQuery's $(document).ready()?
In jQuery, a common pattern is:
$(document).ready(function () {
// code here
});
If I am writing plain JavaScript with no library, what is the proper way to execute one or more functions when the page is ready for DOM manipulation?
Possible alternatives I know about include:
window.onload = myFunction;
or:
<body onload="myFunction()">
or calling the function from a script near the end of the page:
<script>
myFunction();
</script>
What is the correct cross-browser approach, including older and newer browsers, for behavior similar to jQuery's $.ready()?
Short Answer
By the end of this page, you will understand the difference between DOM ready and page fully loaded, how to use DOMContentLoaded in vanilla JavaScript, when window.onload is more appropriate, and how to write a safe helper that works whether the DOM is already loaded or not.
Concept
The main idea behind jQuery's $(document).ready() is simple: run code as soon as the DOM is ready to be used.
The DOM (Document Object Model) is the browser's in-memory representation of your HTML. If your script tries to access elements before the browser has parsed them, code like document.getElementById(...) may fail or return null.
In plain JavaScript, the closest equivalent is usually:
document.addEventListener('DOMContentLoaded', function () {
// DOM is ready
});
Why this matters
There are two common "ready" moments in a page:
DOMContentLoaded: fires when the HTML has been parsed and the DOM is builtload: fires later, when the whole page including images, stylesheets, and other resources has finished loading
For most UI code, event wiring, and DOM manipulation, you want DOMContentLoaded, not load.
Why jQuery had ready()
Older browsers behaved inconsistently, so jQuery wrapped those differences in a simple API. Modern browsers support , so plain JavaScript is enough in most projects.
Mental Model
Think of the browser like a team setting up a room for a meeting:
- HTML parsing is the team putting chairs, tables, and whiteboards into place
- DOM ready means the room layout is finished, so people can start working inside it
- Page load means everything else has also arrived, including decorations, projectors, and snacks
If your code just needs to sit people in chairs, you only need the room layout finished. You do not need to wait for every extra item to arrive.
So:
- Use
DOMContentLoadedwhen you need the structure of the page - Use
loadwhen you need all external resources too
Syntax and Examples
Basic vanilla JavaScript equivalent
document.addEventListener('DOMContentLoaded', function () {
myFunction();
});
This runs myFunction() as soon as the DOM is ready.
Example with a real DOM action
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM Ready Example</title>
</head>
<body>
<h1 id="title">Hello</h1>
<script>
document.addEventListener('DOMContentLoaded', function () {
const title = document.();
title. = ;
});
Step by Step Execution
Traceable example
<div id="message"></div>
<script>
function onReady(callback) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback);
} else {
callback();
}
}
onReady(function () {
const box = document.getElementById('message');
box.textContent = 'Ready!';
});
</script>
Step by step
- The browser reads the HTML.
- It creates the
<div id="message"></div>element in the DOM. - The script runs and defines the
onReadyfunction. onReady(...)is called with a callback function.
Real World Use Cases
Common uses of DOM ready code
Attach event listeners
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('saveBtn').addEventListener('click', saveForm);
});
You need the button to exist before attaching the click handler.
Initialize UI components
document.addEventListener('DOMContentLoaded', function () {
setupTabs();
setupMenu();
});
Many apps initialize navigation, modals, accordions, or forms when the DOM is available.
Read values from the page
document.addEventListener('DOMContentLoaded', function () {
const userId = document.getElementById('user-id').value;
(userId);
});
Real Codebase Usage
How this is used in real projects
Developers usually do one of these:
1. Put scripts at the end of <body>
If a script only depends on elements already written above it, placing it near the end of the document often removes the need for a ready handler.
<body>
<button id="btn">Click</button>
<script>
document.getElementById('btn').addEventListener('click', function () {
console.log('Clicked');
});
</script>
</body>
2. Use defer for external scripts
<script src="app.js" defer></script>
A deferred script downloads in parallel and runs after HTML parsing is complete. This is a very common modern solution.
Common Mistakes
1. Using window.onload when only the DOM is needed
Broken idea:
window.onload = function () {
setupMenu();
};
This works, but it waits longer than necessary.
Better:
document.addEventListener('DOMContentLoaded', function () {
setupMenu();
});
2. Overwriting an existing onload handler
Broken code:
window.onload = firstFunction;
window.onload = secondFunction;
Only the second assignment remains.
Better:
window.addEventListener('load', firstFunction);
window.addEventListener(, secondFunction);
Comparisons
DOM ready vs full page load
| Approach | When it runs | Best for | Notes |
|---|---|---|---|
DOMContentLoaded | After HTML is parsed | DOM queries, event binding, UI setup | Closest to jQuery ready() |
load | After all resources finish loading | Image measurements, full asset readiness | Usually later than needed |
Script at end of <body> | When parser reaches the script | Simple pages | Works if needed elements already appear above |
defer script | After HTML parsing, before DOMContentLoaded completes | Modern external scripts |
Cheat Sheet
Quick reference
Vanilla JS equivalent of jQuery ready
document.addEventListener('DOMContentLoaded', function () {
// DOM is ready
});
Safe reusable helper
function onReady(fn) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
Full page loaded
window.addEventListener('load', function () {
// everything loaded
});
Modern external script loading
<script src="app.js" defer>
FAQ
What is the vanilla JavaScript equivalent of $(document).ready()?
Use:
document.addEventListener('DOMContentLoaded', function () {
// code here
});
Is window.onload the same as DOMContentLoaded?
No. DOMContentLoaded fires when the DOM is built. load fires later, after images and other resources finish loading.
Can I just put my script at the end of the <body>?
Yes, often. If the elements your script needs already appear above it, that is a simple and valid approach.
What if my script runs after DOMContentLoaded already happened?
Check document.readyState and run immediately if the document is no longer loading.
Is body onload recommended?
Usually no. It works, but it mixes HTML and JavaScript and is harder to maintain than using addEventListener.
Do I still need a ready handler if I use ?
Mini Project
Description
Build a small page initializer in vanilla JavaScript that updates text on the page and attaches a button click handler as soon as the DOM is ready. This demonstrates the most common real use of DOM-ready logic: safely finding elements and wiring up interactions without relying on jQuery.
Goal
Create a reusable onReady helper and use it to initialize page content and event listeners safely.
Requirements
- Create an
onReadyfunction that runs a callback when the DOM is ready. - Add a heading and a button in HTML.
- Change the heading text during initialization.
- Attach a click event to the button.
- Show a message in the console when the button is clicked.
Keep learning
Related questions
Can You Style Half a Character in CSS? Text Effects with CSS and JavaScript
Learn how to style half of a character using CSS and JavaScript, including overlay techniques for dynamic text effects.
Check If a Checkbox Is Checked with jQuery
Learn how to check whether a checkbox is checked in jQuery using the correct selector, with examples, mistakes, and practical patterns.
Convert HTML and CSS to PDF in PHP: Options, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose a practical approach for Linux web servers.