Where to place Javascript in a HTML web page


There are three location where JavaScript can be placed for use in a webpage.

  1.     within the head tag
  2.     Within the body tag
  3.     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");
 }

Tags: , ,

Join Us!