JAVASCRIPT PLACEMENT


One can place javascript anywhere in HTML but there are few recommended ways for writting javascript.
    Preffered positions for placing javascript in HTML
  • Script in between <head> and </head> tags.
  • Script in between <body> and </body> tags.

Javascript in <head> and </head> tags.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction(){
alert("HELLO JAVASCRIPT")
}
</script>
<title>
JAVASCRIPT.
</title>
</head>
<body>
<button onclick="myFunction()" type="button" value="function">
Click Me!</button>
</body>
</html>

Output:

Javascript in between <body> and </body> tags.

Javascript can be placed anywhere in the HTML document but few developers use to mention in between body tags so that they can point out mentioned javascript relates to which HTML document.
<!DOCTYPE html>
<html>
<head>
<title>
JAVASCRIPT.
</title>
</head>
<body>
<script type="text/javascript">
function myFunction(){
alert("HELLO JAVASCRIPT")
}
</script>
<button onclick="myFunction()" type="button" value="function">
Click Me!</button>
</body>
</html>

Output:

Mentioning javascript in other file

Few developers use to write javascript in other file so that original script never gets mixed with HTML document.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="filename.js">
<title>
JAVASCRIPT
</title>
</head>
<body>
<button onclick="myFunction()" type="button" value="function">
Click Me!</button>
</body>
</html>

Output: