HTML script tag placement?
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开发者_JAVA技巧 help?
Thanks!
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.
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.
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.
精彩评论