14

Every once in a while I hear about placing HTML <script> tags later in the HTML document rather than in the <head> element.

Some people, or so I've heard, even advocate placing one's scripts as the last few tags before </body>.

Is this due to a performance issue? Perhaps loading up a script is a blocking IO operation, considering that script-dependent scripts are placed after other scripts like so:

<script src="jQuery.js"></script>
<script src="myScriptThatUsesjQuery.js"></script>

Even if that's the case, why would placing one's scripts near the end of the HTML document help?

Thanks!

swaggler
  • 543
  • 1
  • 5
  • 13
  • 1
    possible duplicate of [Where is the best place to put – bluish Mar 26 '13 at 15:31

3 Answers3

12

When a <script> tags appears within <body>, it pauses parsing of the document until it's been loaded (if applicable) and executed. This is so that old scripts which use document.write can do their thing.

Placing <script> tags last in the body keeps them from holding things up.

duskwuff -inactive-
  • 171,163
  • 27
  • 219
  • 269
  • I agree with this. You shouldn't use Javascript for any kind of main functionality for your website (such as displaying large amounts of informative text) so placing it at the bottom will load all your important stuff first and save the flash javascript to load last. – Howdy_McGee Sep 17 '11 at 04:47
4

Well, the <script> should be included before </body> and as you say <script src="jQuery.js"></script> has to be included before the <script src="myScriptThatUsesjQuery.js"></script>, because jQuery.js loads all the functions that are used by myScriptThatUsesjQuery.js, so you can't use a function (eg $()) before it has been declared.

bluish
  • 23,093
  • 23
  • 110
  • 171
kritya
  • 3,162
  • 6
  • 38
  • 58
1

Having a lot of script files in your head tag slows site performance because the HTTP spec advises browsers not to download more than 2 files from any host in parallel. So if you have a half dozen or so .js files being loaded from your site's script folder, the loading of the other resources on your site (images/css etc) are going to be blocked while the browser goes through the list 2x2. It produces a bottleneck, basically.

I think some modern browsers have workarounds for this problem, but until the world gives up on IE6/7, it is probably better to err on the side of optimisation.

TemplateRex
  • 65,583
  • 16
  • 147
  • 283
JHolyhead
  • 945
  • 4
  • 8