Execute code after the page is loaded
Question:
How to execute code after the page is loaded? Answer:
document.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
Description:
To execute any JavaScript code that requires the DOM to be loaded you can use a simple plain vanilla JavaScript event listener. The DOMContentLoaded
event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Using the code above is equivalent to the old jQuery solution:
$('document').ready(function(){
console.log('DOM fully loaded and parsed');
});
Note:
Not to be confused with the load
event that is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.
Reference:
DOMContentLoaded event reference
Share "How to execute code after the page is loaded?"
Related snippets:
- Add class to the clicked element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Go back to previous page with JavaScript
- Execute code after the page is loaded
- Detect fullscreen mode with JavaScript
- Detect Ctrl+C and Ctrl+V using JavaScript
- Detect Ctrl + click in JavaScript
- Detect escape key press in JavaScript
Tags:
page loaded, DOM loaded, vanilla JavaScript, pure JavaScript, document ready, onload Technical term:
Execute code after the page is loaded