Optimized Google Analytics Code

A lot of web sites use Google Analytics to analyze traffic data, so the performance of Google's tracking code is very important. Google recommends to place the code just before closing the <body> tag to ensure "that the tracking code is executed as the last element of the DOM". Otherwise, the script would block the other elements from loading and visitors would have until the script is executed to see the rest of the page. Unfortunately, you can't place the script at the bottom of the page if you some advanced features like tracking events.

To improve the script's performance, Google decided to load it asynchronously. "Unlike a traditional installation, asynchronous tracking optimizes how browsers load ga.js so its impact on user experience is minimized. It also allows you to put your Analytics snippet higher in the page without delaying subsequent content from rendering."

Here's the new code for basic tracking, which uses some ideas from Steve Souders:

<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();

</script>
Google Analytics Blog says that the new snippet is a beta feature and changing the code is optional.
The new tracking snippet offers the following benefits:

* Faster tracking code load times for your web pages due to improved browser execution
* Enhanced data collection and accuracy
* Elimination of tracking errors from dependencies when the JavaScript hasn't fully loaded