Anjan Dutta

How to run a function when the page is loaded in JavaScript

How to run a function when the page is loaded in JavaScript

We can use the onload attribute in body tag to run any javascript function when a page is loaded.

The working code is below.

The HTML

<html>
<head>
<title></title>
</head>
<body onload="onloadFunction()">
Checkout my <a href="https://anjandutta.com">blog</a> for more tutorial.
</body>
</html>

The JavaScript

function onloadFunction() {
alert("page loaded");
}