Home / Google Analytics Asynchronous Tracking

Google Analytics Asynchronous Tracking

Google recently released updated tracking code for Google Analytics which allows for asynchronous tracking. This means the analytics tracking can be done at the same time as rendering other content and therefore won’t delay other page content from rendering. This results in what appears to be faster rendering pages.

Documentation etc

For full documentation and examples please refer to the Google Analytics Asynchronous Tracking page which will always contain the most up to date information. I also include an example here for completeness sake and also to show where the tracker should be placed in relation to the rest of the HTML content.

Example

Here’s what the Javascript tracking code should look like and shows how it should be positioned directly after the opening <body> tag. Obviously the UA-XXXXX-X Analytics account code should be replaced with your actual code and the other elements in the skeleton below (such as the DOCTYPE) should be set with what is relevent for your website.

<!DOCTYPE html>
<html>
<head>
<title>Title goes here</title>

<script type="text/javascript">

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

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();

</script>

</head>

<body>

<!-- body content here -->

</body>
</html>

Benefits

Some of benefits of using this new asynchronous tracking script over the old style tracking script (which goes directly before the closing </body> tag) are:

1) It doesn’t cause any issues with blocking other content rendering while the script downloads and executes. This should make your page appear to load faster and may lead to less people exiting early due to a slow rendering page.

2) Because the tracking code is now at the top of the HTML it will track visitors who may bail out early and who wouldn’t have previously been tracked because the bottom of the document which contained the old style tracking code never loaded.

I’m rolling this out across my websites

I’ve started rolling this new asynchronous tracking out across my websites starting with this blog directly before posting this and it already seems to have improved the perceived speed of the page load.