As we are keeping our JavaScript code inside html pages by using <script> tag, it is upto us to keep our code in any location. However if we want our code to work as soon as the page loads, then we have to keep our JavaScript code inside <head> tag. Here is an sample of simple JavaScript code kept inside head tag.
<html>
<head>
<title>Javascript page structure</title>
<script language='JavaScript' type='text/JavaScript'>
document.write("Hello World")
</script>
</head>
<body>
This is body content
</body>
</html>
The above code will write Hello World as soon as the page loads to the client browser. We can keep the script inside our body tag also . Like this
<html>
<head>
<title>Javascript page structure</title>
</head>
<body>
This is body content
<script language='JavaScript' type='text/JavaScript'>
alert("Hello World")
</script>
</body>
</html>
Let us change this a bit and use one alert message inside a function. Like this.
<html>
<head>
<title>Javascript page structure</title>
<script language='JavaScript' type='text/JavaScript'>
function start(){
alert("Hello World")
}
</script>
</head>
<body >
This is body content
</body>
</html>
You can see above code will not display the alert message because we have kept the message inside a function and we need to call the function. To call the function onload we have to use the body tag like this.