Placement of Script Tag in HTML File

JavaScriptIt is a very common question where you should place your script tag.  Few people prefer placing it after head tag and few prefer placing it somewhere in the body tag.  If there is no manipulation of HTML elements on page load, then it is okay to place it in the head tag.  But if there is some manipulation of HTML elements like adding styles, adding event handlers etc, then you should place it right before closing body tag.

In general, a browser engine can download 2 files in parallel as per HTTP/1.1 specification.  This means if you have multiple external JavaScript files and you add their reference in the head tag, then loading of your webpage will be blocked until all those files are completely downloaded.  However, the modern browsers support async and defer attributes for script tag which tells the browser to continue loading the webpage without waiting for scripts to be downloaded.  But it is also true, old browsers do not support these attributes. So, it is good practice to add your script tag before closing body tag for browser compatibility.

There are 2 examples given below.  In first example, we are changing background of button control by placing script tag in the head tag.  In second example, we are adding same script tag before closing body tag.  For your information, first example will not work because you are changing background of a control which has not been loaded yet.

First Example:

<html>
<head>
<title>JavaScript Tutorial </title>
<script type="text/javascript">
document.getElementById("myBtn").style.backgroundColor = "red";
</script>
</head>
<body>

<input id="myBtn" type="button" value="ClickMe"/>

</body>
</html>

Second Example:

<html>
<head>
<title>JavaScript Tutorial </title>
</head>
<body>

<input id="myBtn" type="button" value="ClickMe"/>

<script type="text/javascript">
document.getElementById("myBtn").style.backgroundColor = "red";
</script>
 
</body>
</html>