← Back toHTML DOM

Execute code when the document is ready

Written byPhuoc Nguyen
Created
16 Feb, 2020
Last updated
23 Nov, 2023
Category
Level 1 — Basic
Tags
DOMContentLoaded, readyState
Contributors
welenofsky
There are some situations where we need to perform tasks once the document is ready. Here are some examples:
Manipulating the DOM
We can use JavaScript to manipulate the elements on a page once they have fully loaded. For example, we can change the text content of an HTML element, add or remove classes, or even create new elements dynamically.
Initializing plugins and libraries
Many plugins and libraries require that the page's elements be fully loaded before they can be initialized correctly. By waiting for the document to be ready before initializing these plugins and libraries, we can avoid potential errors caused by accessing non-existent elements.
Setting event listeners
We can set up event listeners for user interactions with the page once all necessary resources have been loaded and parsed. For instance, we may want to listen for clicks on a button or submit events from a form.
Making API requests
Fetching data from an external API requires that all resources are loaded first so that any necessary authentication tokens or headers are set correctly before making a request.
To ensure that our code runs smoothly without any errors due to missing resources or uninitialized elements, we need to execute our code only when the document is ready. We can use the `document.readyState` property to check the loading status of the document. It can have three values:
  • `loading` while the document is still loading.
  • `interactive` once it has finished loading and parsing HTML but some resources may not have been loaded yet.
  • `complete` when everything has finished loading.
If the document is still loading, we can add an event listener to wait for the `DOMContentLoaded` event to fire, which signals that all resources have been loaded and parsed. Once this event fires, we can execute a given callback.
If `document.readyState` returns `interactive` or `complete`, indicating that the document has already finished loading, then it simply executes the provided callback without waiting for any events.
Here is a code snippet that provides a custom implementation of checking whether or not the document has finished loading before executing any code.
js
const ready = function (cb) {
// Check if the `document` is loaded completely
document.readyState === "loading"
? document.addEventListener("DOMContentLoaded", function (e) {
cb();
})
: cb();
};

// Usage
ready(function() {
// Do something when the document is ready
...
});
This implementation is useful because it lets us run our code as soon as all the necessary resources are available, while avoiding errors that can result from trying to access elements that haven't been created yet.
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn