In the dynamic world of web development, ensuring a seamless user experience is crucial. One way to achieve this is by executing scripts after the page has been loaded.
Let's explore different methods to achieve this in JavaScript.
Window Load Event
One of the most reliable ways to execute scripts after the entire page, including images and other resources, has loaded is by using the window load event.
Here's an example.
window.addEventListener('load', (event) => {
// Your script logic goes here
alert('this alert is fired after page load');
});
This ensures that the script will only run once all assets on the page have been fully loaded.
In this above snippet, the window is attached to addEventListener() method sets up a function that will be called whenever the specified event is delivered to the target.
Another way to achieve the same objective is to use window.onload event handler.
Take a look at the snippet below.
window.onload = function () {
// Your script logic goes here
alert('Page has loaded.');
};
DOMContentLoaded Event
If you want to execute scripts after the DOM (Document Object Model) has been constructed but before all resources have finished loading, you can use the DOMContentLoaded event:
window.addEventListener('DOMContentLoaded', (event) => {
// Your script logic goes here
alert('this alert is fired after DOM loaded');
});
By understanding the different events and best practices, you can implement this technique effectively in your web development projects.