Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.

But where exactly and when?

Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?

like image 915
e-satis Avatar asked Sep 27 '08 12:09

e-satis


People also ask

Where should JS script be placed in HTML?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

Should JavaScript be at top or bottom of page?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Why is the JS at the bottom of HTML?

By placing the JS at the bottom of your page before the closing </body> tag, you are allowing the HTML to be parsed prior to loading the javascript. This gives the effect of faster page load times.


1 Answers

There are two possibilities for truly unobtrusive scripts:

  • including an external script file via a script tag in the head section
  • including an external script file via a script tag at the bottom of the body (before </body></html>)

The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.

If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.

And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.

like image 174
domgblackwell Avatar answered Sep 28 '22 02:09

domgblackwell