18

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!

1

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.