- Instant help with your JavaScript coding problems

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.

 

Share "How to execute code after the page is loaded?"