The window.onload
event in JavaScript is triggered when the whole web page, including all its content (such as images, scripts, and stylesheets), has finished loading. You can use this event to execute a function or perform certain tasks once the page has completely loaded.
Here’s the syntax for using the window.onload
event in JavaScript:
window.onload = function() {
// Code to be executed when the page finishes loading
};
window.onload
is the event property that represents theload
event of thewindow
object.- The
=
operator is used to assign a function to thewindow.onload
property. function()
is an anonymous function that will be executed when theload
event is triggered.- The code inside the function’s curly braces
{}
represents the tasks or actions you want to perform when the page finishes loading.
Alternatively, as mentioned earlier, you can use the addEventListener
method to achieve the same result:
window.addEventListener("load", function() {
// Code to be executed when the page finishes loading
});
Window onload JavaScript example
Simple example code that demonstrates the usage of window.onload
event in JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Window onload Example</title>
</head>
<body>
<h1>Window onload Example</h1>
<script>
// Attach an event handler to the window.onload event
window.onload = function() {
// Code to be executed when the page finishes loading
var heading = document.querySelector('h1');
heading.style.color = 'red';
console.log('Page loaded!');
};
</script>
</body>
</html>
Output:
When you open this HTML file in a web browser, the JavaScript code inside the window.onload
event handler will be executed once the entire page has finished loading. In this case, the heading text color will be changed to red, and the message will be logged to the console.
Comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version