Where should I put a Javascript code in an HTML document?

Asked

Viewed 48,488 times

108

Where Javascript code should be placed in an HTML document: in the element <head> or <body>? At the beginning or end of each one? Is there any difference in performance or any other related to it?

4 answers

111


It depends on what the script does, and how much it misses. All Javascript inserted in a page (wherever) runs in a way synchronous by default*. This means that when the tag <script> is found the browser does not render anything else while this script is not loaded and executed.

Put a <script> in the head ensures that it runs before any element is placed on body. That means he guaranteed will be present when the page is "mounted", that is, any code that needs to be present when processing the body you will surely be ready to act. The downside is that the user will only see a blank page until the script is finished running.

Put a <script> at the end of body, on the other hand, it allows the content before it to appear to the user without having to wait for its execution. This passes the impression of a website faster, the user does not need to wait for every little detail to be ready before reading the content of the page. The drawback is that - if your script significantly modifies the content and/or its presentation and functionality - the user will see a "strange" and "poorly formatted" page before the script "fixes it". Similarly, if a script changes the behavior of a link or button, for example, clicking it before the script runs will cause incorrect behavior.

It is then up to you to determine, case by case, where is the best place to place the script. If it makes little difference, the most common recommendation is the end of body, the performance issue mainly. If you are only interested in browsers modern, however, put it in the head with the attribute defer can be even better.


* Note: It is also possible to make the script asynchronous if this is possible (i.e. there are no complex dependencies between the different scripts and/or between the script and the page elements) through the attributes async and defer HTML5. More details in that reply. Both load parallel to rendering, the difference is that the async for rendering (at an arbitrary point) at the time the load is completed to run it, while the defer only executes it at the end of the rendering, even if the load is completed before. As in the synchronous case, the most indicated use depends on its purpose.

  • 1

    I liked your reply, you explained well and quickly how and when scripts are executed in each of the elements.

  • 5

    Good answer! It might be worth adding that Google doesn’t like slow sites. I.e. the less script in head the better.

37

Yes, it makes all the difference!

Ground rule

The basic rule is: most important scripts must come first in the document to run before, and less priority scripts may come later to make the most important content load first.

Recommendation of Yahoo!

Place scripts at the end of the file became popular with the famous Yahoo! document of best practices to optimize a Web Site.

Specifically, that section. The problem is that most developers have not understood that this is recommended in some cases, many people started putting the scripts to load later indiscriminately.

Example of when *no* should the script be put to the end

  • Script for an important ajax request.

  • Script of removal of placeholder. *

Examples of when to put the script to the end

  • Tool script Analytics (most common example, moreover).

  • A script that applies a style to subtitles title (leaving more beautiful than the native browser).


* Many sites have explanatory text in the search bar (called placeholder). Formerly (for now it is HTML5 native) this text was removed when the user clicked in the field. This was done by a script. It has happened to me, more than once, of practically the entire site loaded and, when clicking on the field, the text does not disappear and I have to manually delete the text (something very boring). This happens on sites that leave this script at the end of the document, probably the loading of some heavy element (like a banner) was in front of this script. If this script was higher in the document it would load earlier, and it would probably work when I click.

  • +1 For the link about good practices, but I thought @mgibsonbr explained better the process of executing the scripts

30

All the old answers to this question are right, but there is a better solution that has not been shown in any of them where you do not need to worry about this.

Of course this solution is not compatible with very old browsers and it works only when loading external files. When the script is inline, does not change anything. But no one should put scripts large within the document. Small ones should make no noticeable difference in render time no matter where it is placed.

Of course where to place is a decision of the developer and varies according to the specific need of the page.

Putting at the end of body the main elements of the page and that should be the most relevant can already be rendered before the end of the verification and interpretation of the parts in JS that are usually important only after the end of the page load.

If the JS code is placed at the beginning or middle, the page rendering is blocked until the whole script be analyzed.

Obviously this does not work so well in all cases. It may be that the correct and complete rendering is only possible when the script starts to be executed, that is, part of the rendering is defined in script.

There are several techniques to better control this load and in few cases this recommendation should be followed.

So nothing prevents and, in general, put in the tag <head> is advantageous as long as it charges asymptotically or with delay.

Obviously there are situations where the script accurate be loaded first because it will control and handle page loading and rendering, possibly indicating progress.

Modern technique:

<script src="script.js" defer>

or

<script src="script.js" async>

Documentation on the marking of script.

Behold how it works.

Where can you use the defer.

Where can you use the async.

9

Javascript is run by the browser as soon as the page is loaded, so it’s a good idea to put the scripts (which can be multiple, there is no script limit per page) in a suitable location (yes, there is more than one).

This location can be between the tags and , and yet you have the option to write a file only with the script, save it with the extension. js and then insert the address of this file into your page to use the scripts of this external file.

Javascript in <body>

Script blocks in the middle of the page are quite simple to understand, just for this the example below:

<html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>

As you can see, the example simply puts the content of the paragraph that has id="demo". Initially empty.

Javascript in <head>

If you chose to put your script between tags <head> and </head> means that you may not want your script to be immediately run by the browser, so this script should be a function, which will be waiting to run (one of the most common styles of script...). To show better, example:

<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<button type="button" onclick="displayDate()">Display  Date</button>
</body>
</html>

In this example there is a button, which has as action to call the function displayDate() when pressed.

External Scripts

Finally, if you want to write several functions that you will always use, suddenly it is a good idea to join them all in an external file and only put the address of this file as a reference on the page, as is common to do with css. The only rule for this is that your file must have the . js extension and cannot contain the tags <script></script> Example:

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

It doesn’t have to be one or the other, we can use scripts in body, head and still have a script file attached, working all together!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.