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

95

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

    
asked by Zignd 26.12.2013 в 18:18
source

4 answers

95

It depends on what the script does, and how much it lacks. All JavaScript placed on a page (wherever it is) runs in Synchronous mode by default *. This means that when the <script> tag is found the browser does not render anything else until this script is loaded and Placing a <script> in head ensures that it runs before any element is placed in body . This means that is guaranteed when the page is "mounted", meaning any code that needs to be present at the time of processing body is sure to be ready to take action. The disadvantage is that the user will only see a blank page until the script finishes executing.

Placing a <script> at the end of body , on the other hand, allows content before it to appear to the user without having to wait for it to run. This gives the impression of a faster site, the user does not have to wait for every detail to be ready before reading the contents of the page. The downside is that - if your script significantly modifies the content and / or its presentation and functionality - the user will see a "weird" and "poorly formatted" page before the script "corrects" it. Similarly, if a script changes the behavior of a link or button, for example, clicking on them before the script executes will cause incorrect behavior.

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

* Note: You can also make the script asynchronous if this is possible (ie there are no complex dependencies between the different scripts and / or between the script and the page elements), using the async and defer of HTML5. More details in this answer . Both render the load parallel to the rendering, the difference being that the async for the rendering (at an arbitrary point) at the time the load is completed to execute it, while the defer only executes it at the end of rendering , even if the load is completed before. As in the case of synchronous, the most appropriate use depends on its purpose.

    
answered by 26.12.2013 / 18:37
source
29

Yes, it makes all the difference!

Basic rule

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

Yahoo Recommendation

Placing the scripts at the end of the file has become popular with the famous Yahoo! document best practices for optimizing a Web site .

Specifically, this section . The problem is that most developers do not understand that this is recommended in some cases , a lot of people started putting the scripts to load later indiscriminately.

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

  • Script of a major ajax request.

  • Placeholder removal script. *

Examples of when to put the script to the end

  • Analytics tools script (most common example incidentally).

  • A script that applies a style to title tags (making it look better than the native browser)

* Many sites have explanatory text in the search bar (called placeholder ). Previously (since this is native HTML5 ) this text was removed when the user clicked on the field. This was done by a script. It has happened to me, more than once, from practically all the website loaded and, when clicking on the field, the text does not disappear and I have to manually delete the text (something quite annoying). This happens on sites that leave this script at the end of the document, probably loading some heavy element (such as a banner) was in front of that script. If this script were higher in the document it would load earlier, and would probably work when I clicked.

    
answered by 26.12.2013 в 18:22
25

All the old answers to this question are true. There is a better solution that has not been shown in any of them where you do not have to worry about it.

Of course, this solution is not compatible with legacy browsers. And it only works when loading external files. When script is inline , nothing changes. But no one should put large scripts inside the document. Toddlers should not make a noticeable difference in rendering 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.

Placing 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 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, page rendering is obstructed until all script is parsed.

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

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

Then nothing prevents and, in general, put in tag head is advantageous as long as it loads asynchronously or with delay.

Obviously, there are situations where script needs to be loaded earlier because it will handle and manipulate page load and rendering, possibly indicating progress.

Modern technique:

<script src="script.js" defer>

or

<script src="script.js" async>

Documentation on script .

See how it works .

Where to use defer .

Where to use async .

    
answered by 02.09.2015 в 14:05
8

JavaScript is executed by the browser as soon as the page loads, so it's a good idea to put the scripts (which can be several, there is no script limit per page) in a suitable location (yes, there is more than one).

This location can be between the and tags, and either you have the option to write a file only with the script, save it with the extension .js and then enter the address of this file on 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, with just the following example:

<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 contents of the paragraph that has id="demo". Initially empty.

JavaScript in <head>

If you chose to put your script between the <head> and </head> tags, you might not want your script to be immediately executed by the browser, so this script must be a function, which will be waiting to be executed (one of the most common script styles ...). To better show, 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>

This example has a button, which has the action of calling the displayDate() function when pressed.

External Scripts

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

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

It does not have to be one or the other, we can use scripts in body, head and still have a script file attached, working everything together!

    
answered by 26.12.2013 в 18:45