Unobtrusive JavaScript: – Madara's Ghost Nov 11 '14 at 10:39

7 Answers7

88

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.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
domgblackwell
  • 5,042
  • 1
  • 19
  • 11
  • 13
    Regarding the script having a 'ready' portion. Putting that script at the bottom of the body guarantees the DOM is ready to be manipulated, if you put it in the head, you have to wrap it so that it waits for the DOMReady(or similar) event – Ruan Mendes Nov 23 '10 at 19:17
  • 4
    @Juan Yes is does, but by placing the script at the bottom, you are delaying the DOMReady event by the amount of time needed for the browser to parse the document and process the head elements (200-500ms), before it requests that script. Mainly on the first page load (assuming it can be cached from there). Whereas if you place it in the head. It's likely to be ready much faster. So with HTML5 in mind, if the script has to modify the layout when the DOM is ready, you are now better off with an "async" or "defer" script in the head. – hexalys Jun 01 '13 at 06:53
33

It's never so cut and dry - Yahoo recommends putting the scripts just before the closing </body> tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document). However, if you have some code you want to run on page load, it will only start executing after the entire page has loaded. If you put the scripts in the <head> tag, they would start executing before - so on a primed cache the page would actually appear to load faster.

Also, the privilege of putting scripts at the bottom of the page is not always available. If you need to include inline scripts in your views that depend on a library or some other JavaScript code being loaded before, you must load those dependencies in the <head> tag.

All in all Yahoo's recommendations are interesting but not always applicable and should be considered on a case-by-case basis.

Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
  • 1
    If you have unobtrusive javscript, you won't have inline snippets, the question specifically mentioned unobtrusive. – Ruan Mendes Nov 23 '10 at 19:19
  • 1
    inline ` – Eran Galperin Jun 28 '11 at 21:55
  • @Eric Galperin: What is a good use of inline script tags that is not obtrusive? – Ruan Mendes Jun 29 '11 at 01:06
  • 4
    @Juan obstrusive Javascript means that the UI is broken without it, or that it is embedded in the markup. ` – Eran Galperin Jun 30 '11 at 12:33
  • @Eric: You didn't answer the question, if your script is unobtrusive, there's no need for it to be interlaced within your HTML in the body tag, except for performance optimization. – Ruan Mendes Jun 30 '11 at 17:33
  • 4
    1. My name is Eran not Eric, 2. When you want to pass data to Javascript from a server-side language, in a loop if items for example, you might use ` – Eran Galperin Jul 02 '11 at 20:59
  • T@Eran: my bad. The unobtrusive approach separates data and content and provides data as JSON instead of generating while rendering the view. – Ruan Mendes Jul 03 '11 at 01:59
25

As others have said, place it before the closing body html tags.

The other day we had numerous calls from clients complaining their sites were extremely slow. We visited them locally and found they took 20-30 seconds to load a single page. Thinking it was the servers performing badly, we logged on - but both web and sql servers were ~0% activity.

After a few minutes, we realised an external site was down, which we were linking to for Javascript tracking tags. This meant browsers were hitting the script tag in the head section of the site and waiting to download the script file.

So, for 3rd party/external scripts at least, I'd recommend putting them as the last thing on the page. Then if they were unavailable, the browser would at least load the page up until that point - and the user would be oblivious to it.

Lazlow
  • 3,241
  • 3
  • 21
  • 13
  • 11
    Cool story bro :) But seriously, this is the most compelling argument I've seen for placing script tags at the bottom of the page. – user271608 Jan 05 '11 at 03:29
17

To summarize, based on the suggestions above:

  1. For external scripts (Google analytics, 3rd party marketing trackers, etc.) place them before the </body> tag.
  2. For scripts that affect page layout, place in head.
  3. For scripts that rely on 'dom ready' (like jquery), consider placing before </body> unless you have an edge-case reason to place scripts in head.
  4. If there are inline scripts with dependencies, place the required scripts in head.
Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
Luke W
  • 8,276
  • 5
  • 44
  • 36
6

If you want to tinker with the position of your scripts, YSlow is a great tool for giving you a flavour if it's going to improve or hurt performance. Putting javascript in certain document positions can really kill page load times.

http://developer.yahoo.com/yslow/

skaffman
  • 398,947
  • 96
  • 818
  • 769
5

No it should not be after the </html> as that would be invalid. The best place to put scripts is right before the </body>

This is basically because most browsers stop rendering the page while they eval the script that you provide. So its OK to put non-blocking code anywhere in the page (I'm mainly thinking of things that attach functions to the onLoad event, since event binding is so fast as to effectively be free). A big killer here is at the beginning of the page putting in some ad server script, which can prevent any of the page loading before the ads have totally downloaded, making your page load times balloon

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Laurie Young
  • 136,234
  • 13
  • 47
  • 54
  • You know, if you're really concerned with speed then there will be no

    or

    - the closing tags for these element types are optional. Put the

    – Jim Sep 27 '08 at 15:34
  • 9
    Hopefully Jim is being sarcastic - at any rate, do not take his advice. Well-formed XHTML requires closing tags for every element, including the body and html tags. If your code isn't valid XML, you're doing it wrong. – matt lohkamp Sep 28 '08 at 07:27
  • 6
    No, I'm not being sarcastic. Take a look at the question. It specifies HTML, not XHTML. It's true that valid XHTML requires these things, but valid HTML does not. There is absolutely nothing wrong with choosing HTML and omitting the closing tags for these element types. – Jim Sep 28 '08 at 16:46
2

If you put it at the bottom, it loads last, hence speeding up the speed that the user can see the page. It does need to be before the final </html> though otherwise it won't be part of the DOM.

If the code is needed instantly though, then put it in the head.

It's best to put things like blog widgets at the bottom so that if they don't load, it doesn't affect the usability of the page.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241