There are three location
where JavaScript can be placed for use in a webpage.
- within the head tag
- Within the body tag
- In an external file
If you want to have a
script run if some event occure,like when a user clicks a button, then you will
place that script within the head tag. If you want the script to run when the
page loads, then you will have to place the script within the body tag.We use
External JavaScript files if we want seprate or hide javascript function from html webpage .
An Example Placing Script within head Tag
<html>
<head>
<script type="text/JavaScript">
<!--
function popup() {
alert("Hello I am within Head")
}
//-->
</script>
</head>
<body>
<input type="button"
onclick="popup()"
value="popup">
</body>
</html>
An Example Placing Script within <body> Tag
<html>
<head>
</head>
<body>
<script type="text/JavaScript">
<!--
alert("Hello I am within Head")
//-->
</script>
</body>
</html>
An Example Placing Script within External JavaScript files
<html>
<head>
<script type="text/JavaScript"
src=”script.js”>
</script>
</head>
<body>
<input type="button"
onclick="popup()"
value="popup">
</body>
</html>
Place the following code in script.js
file .
function popup()
{
alert("Hello I am within External file");
}