I decided to write a post about the Google Analytics code, primarily for people new to the web analytics world. Even if this a very old topic that has been exhausted by various renowned bloggers, I realised that a lot of people still struggle to understand the basic differences between Google Analytics tracking code versions.
Hopefully in this post I will clarify the main differences and modifications that you can do to your Google Analytics code, when to use each version, and what you’ll get in return. I will also cover how to do the same modification with Google Tag Manager. If you do not know what Google Tag Manager is, Google recently released a series of videos that will help you understand the basics.
I will not go through the old school Urchin.js code, and dive directly to the codes you are most likely to see in various web sites today.
Google Analytics Classic Asynchronous – The most common GA code
<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'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>
This is the most common code you will find in a web site with Google Analytics tracking code installed. This is the default version that simply fires a page view tag on your web site in order to provide you the information you see in your GA account by default.
Similarly to Universal analytics code, you can re-write your Google Analytics code, and add additional features that suits your needs such as cross-domain tracking, multiple domain tracking, display features, Enhanced link attribution etc. You can read a detailed guide around ga.js on the relevant Google Development Guide in how to add these features.
If for any reason you are using the code above, you are advised to migrate to Google Analytics Universal. You will be getting a full list of additional features and insights such as cross-device tracking, UserID, Enhanced E-commerce and many more you can read here.
In this guide we will explore these additional features and I will provide you with the relevant GA code, so all you have to do is replace UA-XXXX-Y number with your own report ID.
Important note from Google: 100% of Google Analytics properties have been transferred to Universal Analytics, and all new properties will be Universal Analytics properties. If you are still using a legacy tracking library (such as ga.js or versions 1.x of the mobile SDKs), you should strongly consider upgrading your tracking code to get all the benefits of Universal Analytics. At this time, none of the non-Universal Analytics tracking libraries have been officially deprecated. Data received from deprecated libraries will continue to be processed for a minimum of two years following an official deprecation announcement.
Google Analytics Code Placement – Header, Footer and the (not set) visits
One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. The code won’t block your page from loading and by placing it in your header you’ll be more likely to get accurate stats.
I read once in stackoverflow that some people prefer to place it in the header as they are not interested recording visits from people who clicked accidentally a link on a google result and then quickly hit “BACK”.
I disagree with this statement, as I am always interested to find out sources that send unqualified visitors to my sites. If you place it in the footer it will still fire, but if the user takes an action on your page before the pageview tag fires, then you will most likely see (not set) visits in your landing page reports.
(not set) Landing page stats
A (not set) landing page is a session with no pageviews, but most likely with events. If you want to be 100% sure, I advise that you check your event report with a segment of visits with page depth = 0. This should return all the events and if your event tracking is organised you will be able to spot which page causes these errors. This is more likely to happen if you run Google Analytics Classic rather than Universal – this is another reason why you should upgrade.
Google Universal Analytics code (Default)
When to use: If you simply want basic data without additional features and if you still use GA Classic.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview'); </script>
This is the default code provided by Google once you log in to your account area. Similarly to the Classic code discussed at the beginning of this post, it only includes a page-view tag. You can use this code directly from this page but make sure that you replace UA-XXXXX-Y with your Google Analytics property ID before copy pasting to your web site. Once you implement the code to all of your web-pages, GA dashboard should start populating with basic data.
Google Analytics code with Display Features
When to use: This code should be the minimum implementation for you web site.
This one will enable a couple of interesting features in you GA report such as your Re-marketing and Advertising Reporting Features as well as Demographics and Interests reports which you can later use for either display campaigns or in order to get a bit more information about who your visitors are.
I highly recommend for the code below to be the minimum implementation you do, regardless if you are running a PPC campaign or not. You can activate the features without the code, but best practice advises to add it.
Important Note: If you decide to use Display Features you will need to activate the relevant feature in your Google Analytics Profile. You can read how to do that on Google’s detailed guide about enabling demographic features as well as Re-marketing and advertising reports.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script>
Google Analytics code with Subdomain tracking
When to use: If you want to track users across different subdomains.
This is an easy one as you dont need to change anything at all. The “auto” value next to ga create will record all of your subdomain traffic to same the GA property as long as you use the same code. You will need to add your domain name to your referral exclusion list in GA admin panel, otherwise each time someone visits your subdomain, you will be getting referral traffic from your own domain.
The referral exclusion feature works ONLY with GA universal. If you suffer from self-referrals and you have Google Classic, adding your domain to the list will not solve the issue.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-xxxxx-y', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script>
Here is where to add your domain to the exclusion list
Google Analytics code with Enhanced Link Attribution
When to use: If you introduce a lot of navigation elements and are interested in analysing element participation to your conversions and/or other KPIs.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto'); ga('require', 'linkid'); ga('send', 'pageview'); </script>
This will allow you to use the In-page Analytics feature, in other words you will see how people interact with your web site. Ideally you should have different Element IDs on your web site for this feature to work as intended, otherwise you might see a range of clicks instead of fixed numbers per element.
It is not perfect and needs lots of work before it becomes a must-have feature, however if you are not firing event tags on your key page elements and navigation bars then it is nice to have.
Google also released a plug in for Chrome Browser where you can activate and get the data directly from your browser. You can downloand the page analytics plug in here. Again you will need to go to your GA property and activate the relevant Settings.
Here is an example of what you will see in Google Analytics or on your browser if you use the plug-in.
Google Analytics code with Cross Domain Tracking
When to use: If you want to track visitors accross multiple web sites, especially if you use different domains to host your application/conversion pages.
Now this is a complex one. To start with a few words about cross domain tracking. According to Google Cross domain tracking makes it possible for Google Analytics to see sessions on two related sites (such as an ecommerce site and a separate shopping cart site) as a single session. This is sometimes called site linking.
From experience, most of the businesses that need this feature tend to host their web site and lead generation form on different domains thus they are not able to see the whole journey in their GA reports, instead they get high conversions attributed to the Referral channel.
Note that you will need to change the GA code on BOTH domains for this to work.
For this example lets assume two different cases. Your domain is XYZ.com and you want to implement cross domain tracking to:
1) ABC.com and
2) ABC.com and DEF.com.
On your main domain XYZ.com, put the code below for case 1, and then replace lines 7 to 11 with 14 to 18 for case 2.
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto',{‘allowLinker’: true }); ga(‘require’, ‘linker’); ga(‘linker:autoLink’, [‘ABC.com’]); ga('send', 'pageview'); </script> //If you link to 2 web sites then replace lines 7 to 11 with the following: ga('create', 'UA-XXXXX-Y', 'auto',{‘allowLinker’: true }); ga(‘require’, ‘linker’); ga(‘linker:autoLink’, [‘ABC.com’,'DEF.com']); ga('send', 'pageview'); </script>
Now you will need to go to your ABC.com and DEF.com web site and add the following code:
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto',{‘allowLinker’: true }); ga(‘require’, ‘linker’); ga(‘linker:autoLink’, [‘XYZ.com’]); ga('send', 'pageview'); </script> //If you link to 2 web sites then replace lines 7 to 11 with the following: ga('create', 'UA-XXXXX-Y', 'auto',{‘allowLinker’: true }); ga(‘require’, ‘linker’); ga(‘linker:autoLink’, [‘XYZ.com’,'DEF.com']); ga('send', 'pageview'); </script>
Your Google analytics report will now start receiving data from all three domains ABC.com, XYZ.com and DEF.com. Beware that you might suffer from self-referral issues. Make sure you exclude the domain names from the report as shown on the sub-domain example above. You might need to create a couple of different GA profiles via filtering but I will cover that on another post.
Google Analytics code with Custom Dimension
When to use: If you have “logged in” user areas and want to do further analysis on a particular audience group that visits an exclusive area in your web site.
Custom dimensions is one of the most powerful features in GA. It allow you to combine any data you want (e.g. CRM data) in a customised way that makes sense to you and your stakeholders.
For example, if your web site prompts users to register for an account or log in to a membership area, by adding a custom dimension to your Google anaytics code you will be able to see when that audience come to the web site, how they engage with your content, run cohort reports for further analysis, etc.
Use the code below to the logged in area of your web site (the code example below includes display features and enhanced link attribution).
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXX-X'); ga('require', 'linkid'); ga('require', 'displayfeatures'); ga('send', 'pageview', { 'dimension1': 'Registered Users' }); </script>
Make sure that this is added ONLY to your membership area and not the whole web site. You can replace the number “1” with any of your 20 custom dimensions (assuming you are a free GA user) but remember to set this up to the GA admin panel as well otherwise it will not work:
If you do not wish to have enhanced link attribution and/or display features on (not sure why you would do that) and only want to fire the Custom Dimension then remove the relevant lines from the code as shown below:
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXX-X'); ga('send', 'pageview', { 'dimension1': 'Registered Users' }); </script>
Wrapping up all Google Analytics tracking code modifications
To wrap it up, you can customize your code as you want. All you need to make sure is that you add the additional features you want under the page view tag as shown below:
ga('require', 'displayfeatures'); //for display features ga('require', 'linkid'); // for enhanced link attribution ga('send', 'pageview', { 'dimension1': 'Registered Users' // for custom dimensions }); ga('create', 'UA-xxxxx-y', 'auto'); // use this instead of ga('create', 'UA-XXXX-Y); if you want to enable sub-domain tracking ga('create', 'UA-XXXXX-Y', 'auto',{‘allowLinker’: true }); // use this for Cross domain tracking ga(‘require’, ‘linker’); // part of same code ga(‘linker:autoLink’, [‘XYZ.com’]); // part of same code
UPDATE:
Google Analytics Tracking code with Adblock Tracking
Found this extremely useful post by GA Evangelist Avinash Kaushik where he discuss in detail AdBlock tracking.
The code below will track adblocks and will also create a Custom Dimension for AdBlockers so you can do further analysis on how adblocking affects your web site’s revenue (assuming you are a publisher) and user experience. Once you implement the code below you will need to create a custom dimension in Google Analytics and replace ZZ with your Custom Dimension number and the XXXX-Y with your GA property ID.
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); // Creates an adblock detection plugin. ga('provide', 'adblockTracker', function(tracker, opts) { var ad = document.createElement('ins'); ad.className = 'AdSense'; ad.style.display = 'block'; ad.style.position = 'absolute'; ad.style.top = '-1px'; ad.style.height = '1px'; document.body.appendChild(ad); tracker.set('dimension' + opts.dimensionIndex, !ad.clientHeight); document.body.removeChild(ad); }); // TODO: Replace UA-XXXXX-Y with you tracking ID. // and replace XX with the index of the custom dimension you created. ga('create', 'UA-XXXXX-Y', 'auto'); ga('require', 'adblockTracker', {dimensionIndex: ZZ}); ga('send', 'pageview');
Tracking Code Implementation via Google Tag Manager
Firstly I suggest you read how to create a macro for your GA properties and how to use a Lookup Table macro to save time when using multiple reports, as this will come very handy in multiple situations when using GTM for GA tracking.
Below is a screenshot of a GA Universal tracking tag (default in GTM) and all the necessary fields you need to fill in, in order to activate Display features, Cross domain tracking and enhanced link attribution.
If you have never done this before here is a step by step guide that will help you Install Google Analytics Universal with Google Tag Manager.
I have left e-commerce implementation out as it is way more complex and deserves its own post, which I promise to deliver very soon.
Happy GA implementation!