Calling JavaScript when a webpage loads

There are a couple opportunities for calling a JavaScript function or running JavaScript coded when a web page loads in a person’s web browser.

One method is to run a script using the body tag’s onload event. Here are a couple examples:

<!-- Call a function -->
<body onload="sayHello();">
<!-- Run multiple commands -->
<body onload="var hello_world='Hello World!'; alert(hello_world);">

Or you can take advantage of the window.onload event. Here are a couple examples:

<script type="text/javascript">
 
	// Call a function with the window onload event
	window.onload = sayHello();
 
	function sayHello(){
 
		alert("Hello World!");
 
	}
 
</script>
<script type="text/javascript">
 
	window.onload = function(){
 
		alert("Hello World!");
 
	};
 
</script>