AnonymousOct 02, 2022
The onload event runs when the whole web page (HTMl) has loaded, including all dependent resources such as css, scripts, iframes, and images.
For example: Developers need to show the welcome message to the user on page load, and the developer needs to call a JavaScript function after the page load event.
There are three ways to call a function when a web page loads in JavaScript.
Follow the below syntax to use onload event in the <body> tag.
<body onload="myFunction()">
<!DOCTYPE html >
<html>
<head>
<title>Onload Event</title>
</head>
<body onload="myFunction();">
<h1>This is a simple web page.</h1>
<script>
// This function will change the background color to blue.
function myFunction() {
alert("welcome to the techstackkit!");
document.body.style.backgroundColor = 'blue';
}
</script>
</body>
</html>
Follow the below syntax to use the window.onload event
window.onload = () => {
// call the function on the page load
};
OR
window.addEventListener('load', () => {
// call the function on the page load
});
OR , You can also use an anonymous function as shown in the example
function myFunction() {
// code to execute on the page load
}
window.onload = myFunction;
<!DOCTYPE html >
<html>
<head>
<title>Window onload Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
function myFunction() {
alert("welcome to the techstackkit!");
}
// Use window.onload to call the function when the page loads
window.onload = () => {
myFunction()
};
</script>
</body>
</html>
Follow the below syntax to use the DOMContentLoaded event
document.addEventListener("DOMContentLoaded", function () {
// call the function on the page load
});
OR
// Use DOMContentLoaded to call the function when the DOM is ready
document.addEventListener("DOMContentLoaded", myFunction);
<!DOCTYPE html >
<html>
<head>
<title>DOMContentLoaded Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
// Define a function to be called when the DOM is ready
function myFunction() {
alert("welcome to the techstackkit!");
}
// Use DOMContentLoaded to call the function when the DOM is ready
document.addEventListener("DOMContentLoaded", function () {
myFunction()
});
</script>
</body>
</html>
Here, we've outlined three ways to make a function start when a page loads. The first one fits well into HTML code, the second one is suitable for JavaScript code, and the third one is the most effective for our goal.
Moreover, with the third approach, users have the choice to change the event to trigger a function on a specific happening. Another perk of this last method is that users can apply it to a single HTML element, not just the entire document, saving them from needing to set up the event listener on every page.