The location of choice of header or body is very simple. If you want to have a script to be executed when they are called, or when an event is triggered, then, you will place that script in the header section. This ensures that the script is loaded before anyone uses it.
On the other hand, if you want the script to be executed when the page loads, then you will want to place the script within the body section.
Here's a basic example of adding JavaScript to the header section of the HTML document.
The JavaScript in the header section runs only when it is called or an event is triggered.
<html>
<head>
<script type="text/javascript">
<!--
function myscript () {
alert("Hello!");
}
//-->
</script>
</head>
<body>
</body>
<html>
The onClick attribute in the code above is called JavaScript event handler. Event handlers allow you to detect when a given "event" has occured.
In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to the element.
Here's a basic example of adding JavaScript to the body section of the HTML document.
The JavaScript in the body section runs as soon as page loads.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
alert("Hello!");
//-->
</script>
</body>
<html>
Sometimes you might want to run the same JavaScript on many pages or through the entire site, but don't want to rewrite the same code on every page.
To simplify this, you can write the code in an external file, and save the file with a .js file extension. Then, link to it from your HTML document.
To use the external script, point to the .js file in the "src" attribute of the <script> tag:
Note: The external script cannot contain the <script> tag!
function myscript () {
alert("Hello!");
}
<html>
<head>
<script src="myjs.js"></script>
</head>
<body>
</body>
</html>