How to usethe DOMContentLoaded event in Javascript
The DOMContentLoaded event is triggered when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This event can be used to run JavaScript code as soon as the page’s HTML has been loaded.
Syntax:
document.addEventListener('DOMContentLoaded', function() {
...
});
Example: This example illustrates the use of the DOMContentLoaded event to make the JS code run after the page load.
HTML
<!DOCTYPE html> < html > < head > < title > Using the DOMContentLoaded event </ title > </ head > < body > < h1 style = "color:green" > w3wiki </ h1 > < h1 > Using the DOMContentLoaded event </ h1 > < p id = "message" ></ p > < button onclick = "location.reload()" > Refresh Page </ button > < script > document.addEventListener('DOMContentLoaded', function () { setTimeout(function () { document.getElementById('message').innerHTML = 'The page has finished loading! After 5 second'; }, 5000); // Delay of 5 seconds }); </ script > </ body > </ html > |
Output:
How to Execute After Page Load in JavaScript ?
JavaScript is often used to add dynamic functionality to web pages, but it can be frustrating when the code runs before the page has finished loading. This can cause errors or unexpected behavior. Fortunately, there are several approaches you can take to ensure that your JavaScript code runs after the page has loaded.
To accomplish this task, the following approaches will be used:
Table of Content
- Using the window.onload event
- Using the DOMContentLoaded event