Where should I put <script> tags in HTML markup?

Viewed 735480

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.

So, where is the right place to put the <script> tags?

(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)

21 Answers

Just before the closing body tag, as stated on Put Scripts at the Bottom:

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

The modern approach in 2019 is using ES6 module type scripts.

<script type="module" src="..."></script>

By default, modules are loaded asynchronously and deferred. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.

The differences between a script and a module are described here:

Classic scripts vs. module scripts in JavaScript

The execution of a module compared to a script is described here:

Modules are deferred by default

Support is shown here:

Can I use... Support tables for HTML5, CSS3, etc

If you are using jQuery then put the JavaScript code wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.

The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the HTML in document,

Also loading the JavaScript files externally has its own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.

But modern browsers also support some other optimal ways, like async and defer to load external JavaScript files.

Async and Defer

Normally HTML page execution starts line by line. When an external JavaScript <script> element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using the defer and async attribute.

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing, but it will be execute only after full HTML parsing is done.

<script src="/local-js-path/myScript.js" defer></script>

Async

When the async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes

  • If your script is independent of other scripts and is modular, use async.
  • If you are loading script1 and script2 with async, both will run parallelly along with HTML parsing, as soon as they are downloaded and available.
  • If your script depends on another script then use defer for both:
  • When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
  • Then script2 will execute after script1 is fully executed.
  • Must do this if script2 depends on script1.
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.

Reference: External JavaScript JS File – Advantages, Disadvantages, Syntax, Attributes

It turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).

The most conservative (and widely accepted) answer is "at the bottom just before the ending tag", because then the entire DOM will have been loaded before anything can start executing.

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.

It depends. If you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it at the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it at the bottom.

Or the best thing (if that's not a concern) is you can make a modal loading box, place your JavaScript code at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.

Including scripts at the end is mainly used where the content/ styles of the web page is to be shown first.

Including the scripts in the head loads the scripts early and can be used before the loading of the whole web page.

If the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.

Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straightforward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow, but now at Google).

The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute the JavaScript code.

<script> ... your code here ... </script>
</body>

And if you write in jQuery, the following can be in the head document and it will execute after the document loads:

<script>
    $(document).ready(function(){
        // Your code here...
    });
</script>

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.

The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load.

Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.

Always, we have to put scripts before the closing body tag expect some specific scenario.

For Example :

`<html> <body> <script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> </body> </html>`

Prefer to put it before the </body> closing tag.

Why? As per the official doc: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics#a_hello_world!_example

Note: The reason the instructions (above) place the element near the bottom of the HTML file is that the browser reads code in the order it appears in the file.

If the JavaScript loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems. Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency. To learn more about alternative approaches, see Script loading strategies.

Related