Google Analytics Implementation – Tracking code (Part 2)

Welcome to Part 2 where we’ll look at the Google Analytics tracking code. You can view the previous chapter of the guide:

1. Google Tag Manager

2. Tracking code

Note: For all tracking code examples we’ll use the GA asynchronous tracking code.

The basic GA tracking code

It used to make sense for all simple single domain websites to use the basic GA tracking code without any modifications. You just select your account, go to Admin and click on the Tracking Info tab. This is how the basic tracking code looks like, where XXXXXX-Y is your property ID:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
_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);
})();

* Replace UA-XXXXXX-Y with your property ID and don’t forget to add the opening and closing JavaScript tags.

 

Adjusting bounce rate

There are some other options you can tweak right on that page, like subdomain and cross-domain tracking, AdWords remarketing through GA and custom campaign tags. We’ll look at something else now – bounce rate adjustment according to time spent on site.

The bounce rate is a really important metric used to evaluate the quality of traffic and landing pages. It shows how relevant your content is for the visitors and how engaged they are with your website.

A bounce is just one hit on your website. And there are two ways to measure it – as a single pageview and as a minimum time spent on the site. The standard GA script tracks a single pageview. Google Analytics, as other web analytics softwares, use timestamps to measure time on pages. It will take the timestamp of the initial hit on the page (e.g. 10:34:10) and the timestamp of the next engagement hit (e.g. 10:35:20) and subtract them to get the actual time on page (1 minute and 10 seconds). When there’s just one hit, there’s no second timestamp and Google Analytics counts this visit as a bounce and time on site is 0:00.

The truth is many visitors (almost half of those bounces) did really paid attention to your website before leaving it. This is valid especially for blogs, where new and regular visitors come, read an article which could be a longer one and take 10-15 minutes, then leave. And there is a way to track this, recommended as best practice by GA themselves (back in July 2012).

By adding one line to our basic GA tracking code, which executes an event when a user has spent over a certain amount of time on the page. You should determine this amount of time depending on your website and what you think is enough time to consider the visitor successfully engaged with your content – 10, 15 seconds or a few minutes.

When this event is executed, the visitor will no longer be counted as a bounce, because the hits are two now – one pageview and one event. And the bounce rate metric will show the real bounces who didn’t spent the required minimum time on the website.

Here’s how we should adjust the code to track minimum time on site (GA uses milliseconds to track time, so we are using 15,000 milliseconds in this case which are equal to 15 seconds):

 

 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
 _gaq.push(['_trackPageview']);
 setTimeout("_gaq.push(['_trackEvent', '15_seconds', 'read'])",15000);

 (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);
 })();

 

* Replace UA-XXXXXX-Y with your property ID and don’t forget to add the opening and closing JavaScript tags.

* If you have a very big site that generates millions of hits be careful with this implementation. The free GA has a limit of 10 million hits per month (hit being pageview, event, virtual pageview, ecommerce transaction, etc.) and if you’re close to this monthly number you may want to consider GA Premium.

 

In-Page Analytics – Enhanced Link Attribution

The In-Page Analytics report is available under the Content section and it’s a visual representation of how visitors interact with your pages. It gives us information about the design layout usability, are visitors focusing on the right content and are they engaging with our call to actions, what are they clicking on the page.

Until November 2012, the In-Page Analytics feature had some flows – it showed clickthrough information by URL and not by the actual link on the page. It also had clickthrough information only on links and not on other elements like buttons. So if you have two or more links to the same URL, Google Analytics shows the combined statistics for both links without distinguishing between one and the other and which of them the visitor actually clicked.

To fix this, you need to customize your tracking script by adding two lines of code and enable the feature in the web property settings. With these changes In-Page Analytics will be able to distinguish between multiple links to the same URL, attributing the right number of clicks to each link; provide click-through information even when redirects are being used; click-through information for other elements such as buttons or navigations that were triggered by JavaScript code. Here are the changes:

 

 var _gaq = _gaq || [];
 var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
 _gaq.push(['_require', 'inpage_linkid', pluginUrl]);
 _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
 _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);
 })();

 

* Replace UA-XXXXXX-Y with your property ID and don’t forget to add the opening and closing JavaScript tags.

 

Additionally, to enable enhanced link attribution:

  • Click Admin at the top of any GA page.
  • Click Property Settings tab.
  • In the In-Page Analytics section, select the Use enhanced link attribution option.
  • Click Apply.
Enhanced link attribution setup

Enhanced link attribution setup

 

Track subdomains

After struggling for couple of months with a subdomain tracking implementation that resulted in self referrals, I found the best article on the subject by Jeremy Aube at the ROI Revolution blog. He explains why the code modifications recommended by Google Analytics have issues, focusing on 3 specific elements: why turning off hashing is bad, how to use the leading period in the _setDomainName command and why subdomain tracking without _addIgnoredRef causes self-referrals (my pain point at the time). So if you want to track subdomains here’s the customized GA tracking code you need to use:

 

   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
   _gaq.push(['_setDomainName', 'domain.com']);
   _gaq.push(['_addIgnoredRef', 'domain.com']);
   _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);
   })();

 

* Replace UA-XXXXXX-Y with your property ID and domain.com with your actual domain name. Don’t forget to add the opening and closing JavaScript tags.

 

Track multiple domains

In case you need to track across multiple domains and subdomains, you need to customize your GA tracking code as well. For example you may want to track together your main website (www.domain.com), your blog (blog.domain.com) and your shopping cart (shop.domain2.com)

Here’s the cross-domain tracking examples for domain.com and domain2.com

domain.com and all subdomains of domain.com (like blog.domain.com):

 

   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
   _gaq.push(['_setDomainName', 'domain.com']);
   _gaq.push(['_setAllowHash', false]);
   _gaq.push(['_setAllowLinker', true]);
   _gaq.push(['_addIgnoredRef', 'domain.com']);
   _gaq.push(['_addIgnoredRef', 'domain2.com']);
   _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);
   })();

 

domain2.com and all subdomains of domain2.com (if such exist):

 

   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
   _gaq.push(['_setDomainName', 'domain2.com']);
   _gaq.push(['_setAllowHash', false]);
   _gaq.push(['_setAllowLinker', true]);
   _gaq.push(['_addIgnoredRef', 'domain.com']);
   _gaq.push(['_addIgnoredRef', 'domain2.com']);
   _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);
   })();

 

* Replace UA-XXXXXX-Y with your property ID and domain.com and domain2.com with your actual domain names. Don’t forget to add the opening and closing JavaScript tags.

 

Don’t forget to modify the links between domains. The easiest way to do this is to have the following onclick attribute in the link:

onclick=”_gaq.push([‘_link’, this.href]); return false;”

 

It’s generally preferred to accomplish linking between domains in a more dynamic way. You might be able to build this into a template driven site, or use a script that modifies onclick attributes of links dynamically.

 

Track custom variables

With custom variables you can further refine GA tracking like defining additional segments. There are different custom variables you can define – for example track logged in users, who shares your content on social media, or how people who were exposed to different variations in an A/B test behave.

Also, you should define a scope for every custom variable, meaning at what level it should apply – pageview, session or visitor level. When you set up visitor level variables it’s a good practice to do it in your main GA tracking code to save one additional hit. Here’s how the code should look like:

 

 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
 _gaq.push(['_setCustomVar',2,'Member type','Logged-in',1]);
 _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);
 })();

 

* Replace UA-XXXXXX-Y with your property ID and the custom variable settings with your own. Don’t forget to add the opening and closing JavaScript tags.

 

It’s important that the custom variable is set before the _trackPageview function.

 

Google Analytics AdWords Remarketing

If you use Google AdWords you’re most probably familiar with the concept of remarketing. With the changes from July 2012 you’re now able to create remarketing lists from the Google Analytics interface – based on metrics like pages viewed, visit duration and conversions. All you need to do is:

  • change one line in your GA tracking code
  • update your privacy policy

Here’s how you need to tweak your GA code:

 

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

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

 

Important note: the DoubleClick cookie – doubleclick.js file is blocked by most default ad blocking software and thus all visitors who use this type of software won’t be tracked at all in GA reports, resulting in drop in visitors (how big the drop will be depends on the type of your site). There are some workarounds and hacks to work with the ad blocking software at LunaMetrics and Andre Scholten blogs. You may also leave your existing code as is and create a separate GA ID, implement a second tracking code with remarketing using Google Tag Manager, then compare your visitors metrics to understand what part of your visitors are not being tracked due to ad blocking software.

 

Track multiple devices

Google’s new Universal Analytics allows you to track users between multiple devices and touch-points (even offline). You can gain insights into the performance of your mobile apps and combine online and offline interactions to understand which channels work best. Universal Analytics script is more flexible and provides more customization options.

In March this year Universal Analytics went out of private beta into public beta and now when you set up a new account you have the option to choose Universal Analytics tracking code or Classic Analytics.

The Universal Analytics tracking code is a bit different and looks like this (always create a new web property dedicated to Universal Analytics XXXXXX-YY):

 

  (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-XXXXXX-YY', 'domain.com');
  ga('send', 'pageview');

 

It’s recommended not to switch right away from Classic (ga.js) to Universal Analytics (analytics.js), but to have both of them running concurrently to maintain continuity in your original account and better understand the differences between the two types of analytics. You need to send the data sets to separate properties: UA data to a dedicated UA property, and ga.js data to a non-UA property. Data cannot be merged or reprocessed after it’s collected.

As Universal Analytics can take a long time to cover, we’ll focus on the Classic Google Analytics. You can always check the UA support section and documentation.

I know it’s often overwhelming and a lot to go through at once and decide what’s right for your website. So the easy way is to answer these questions:

  • Do you want to adjust bounce rate (recommended)?
  • Do you want to take advantage of enhanced in-page analytics settings?
  • Do you want to use GA remarketing?
  • Do you want to track custom variables?
  • Do you need to track subdomains?
  • Do you need to track multiple domains (where’s your shopping cart located)?
  • Do you need to track multiple devices (Universal Analytics)?

 

Go to the next chapters of the guide:

3. Check the implementation
4. Profiles and filters
5. Settings
6. Goals setup
7. Virtual pageviews and events
8. Campaign tracking
9. Advanced segments and custom reports. Dashboards.
10. Custom alerts

Or jump to the whole thing: Google Analytics Implementation Guide.

Still have questions? You can ask them as comments below and I’ll try to answer.

is a Google Analytics fan, who also loves SEO, conversion optimization, online marketing and social media. You can follow her on Twitter and LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>