Javascript - <script> Tag Placement

Introduction

Traditionally, all <script> elements were placed within the <head> element on a page, such as in this example:

<!DOCTYPE html> 
<html> 
  <head> 
    <title>Example HTML Page</title> 
    <script type="text/javascript" src="example1.js"></script> 
    <script type="text/javascript" src="example2.js"></script> 
  </head> 
  <body> 
    <!-- content here --> 
  </body> 
</html> 

Including all JavaScript files in the <head> means that all of the JavaScript code must be downloaded, parsed, and interpreted before the page begins rendering.

This can cause a noticeable delay in page rendering, and the browser will be completely blank.

For this reason, modern web applications typically include all JavaScript references in the <body> element, after the page content:

<!DOCTYPE html> 
<html> 
  <head> 
    <title>Example HTML Page</title> 
  </head> 
  <body> 
    <!-- content here --> 
    <script type="text/javascript" src="example1.js"></script> 
    <script type="text/javascript" src="example2.js"></script> 
  </body> 
</html> 

Using this approach, the page is completely rendered in the browser before the JavaScript code is processed.

Related Topics