Green Files

Where should I put JavaScript code in an HTML document?

Day: 06/01/2022 - Time: 15:00:26

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

It depends on what the script does, and how much it is needed. All JavaScript inserted into a page (wherever it is) runs <b>synchronously</b> by default*. This means that when the <i><script></i> tag is encountered the browser does not render anything else until this script is loaded and executed.

Placing a <i><script></i> in the <i>head</i> ensures that it is executed before any elements are placed in the <i>body</i>. This means that it is <b>guaranteed</i> to be present when the page is "assembled", that is, any code that needs to be present when processing the <i>body</i> will surely be ready to act. The downside is that the user will only see a blank page until the script finishes executing.

Placing a <i><script></i> at the end of the <i>body</i>, on the other hand, allows the content before it to already appear to the user without having to wait for it to be executed. This gives the impression of a faster site, the user does not have to wait for every little detail to be ready before reading the page content. 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 "fixes" it. Likewise, 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 is then up to you to determine, on a case-by-case basis, where is the best place to place the script. If it makes little difference, the most common recommendation is the end of the <i>body</i>, mainly for performance reasons. If you're only interested in modern browsers, however, putting it at the <i>head</i> with the <i>defer</i> attribute might be even better.

*It is also possible to make the script asynchronous, if that is possible (i.e. there are no complex dependencies between the different scripts and/or between the script and the page elements), through the HTML5

<i>async</i> and <i>defer</i> attributes. More details in this answer. Both do the load parallel to the rendering, the difference is that the <i>async</i> stops the rendering (at an arbitrary point) at the moment when the load completes to execute it, while the <i>defer</i> only executes it at the end of the rendering, even if the charge is completed sooner. As in the synchronous case, the most suitable use depends on your purpose.

Reference:

https://pt.stackoverflow.com/questions/1109/onde-devo-colocar-um-c%c3%b3digo-javascript-em-um-documento-html

GO UP
GO TO INDEX