Edit: While this question has been asked and answered before (1), (2), (3), the answers have not mentioned the possibility of using asynchronous and /or lazy loading when including files in the <head>
. I was prompted to ask the question due to Google analytics new code which uses both of these methods.
I recently noticed that Google analytics is now suggesting including its Javascript snippet right before the </head>
tag. They used to suggest including the snippet right before the </body>
tag.
The YUI Best Practices for Speeding Up Your Web Site suggests putting scripts as far down the page as possible, since scripts can block parallel downloads:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
Google says:
One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the
<head>
section, and we recommend placing the snippet at the bottom of the<head>
section for best performance.
I'm generally more concerned with user experience and page load speed than making sure each and every tracking beacon is sent, so this would push me toward including the Google analytics script toward the bottom of the page, instead of in the <head>
, right?
I'm sure there's more things to consider than these two points of view. What are the things influencing you? What are the things to consider?
So, what are the pros and cons of having your scripts right berfore </head>
versus right before </body>
?