To check if the document is ready and run some code, you can add an event handler to the DOMContentLoaded event of the document object.

The DOMContentLoaded event is fired when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

// Define event handler
const handler = (e) => {
    console.log(`Document is ready!`);
};

// Listen for `DOMContentLoaded` event
document.addEventListener('DOMContentLoaded', handler);

If you are not interested in reusing the event handler function, just replace it with an anonymous function as shown below:

// Listen for `DOMContentLoaded` event
document.addEventListener('DOMContentLoaded', (e) => {
    console.log(`Document is ready!`);
});

The DOMContentLoaded event works in all modern browsers, including IE9 and above.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: