published: 01 Aug 2022
2 min read
How to check if document is ready using JavaScript
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.
Are we missing something? Help us improve this article. Reach out to us.
How to check if document is ready using JavaScript
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.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur