Put JavaScript at the bottom

By:    Updated: January 23,2017

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

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript at the top</title>
    <script type="text/javascript" src="valinv_1.js"></script>
    <script type="text/javascript" src="valinv_2.js"></script>
</head>
<body>
    <!-- body content -->
</body>
</html>

The main purpose of this format was to keep external file references, both CSS files and JavaScript files, in the same area. However, including all JavaScript files in the <head> of a document means that all of the JavaScript code must be downloaded, parsed, and interpreted before the page begins rendering (rendering begins when the browser receives the opening <body> tag). For pages that require a lot of JavaScript code, this can cause a noticeable delay in page rendering, during which time 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, as shown in this example:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript at the bottom</title>
</head>
<body>
    <!-- body content -->
    <script type="text/javascript" src="valinv_1.js"></script>
    <script type="text/javascript" src="valinv_2.js"></script>
</body>
</html>

Using this approach, the page is completely rendered in the browser before the JavaScript code is processed. The resulting user experience is perceived as faster, because the amount of time spent on a blank browser window is reduced.

 

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. If many scripts depend on other same script such as jQuery, we can put jQuery at top.

 

If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

More in Development Center
New on Valinv
Related Articles
Sponsored Links