Adding Google Analytics to your Website

Overview

Google Analytics provides a lot of insight into your user base for free. Setting up the service is a breeze, but it can be confusing digging into some of the custom functionality. This article should get you started and show you some tips and tricks on hooking into some of the customized functionality in GA.

Account Setup

Navigate to the Google Analytics website. If you don’t already have a Google account, sign up for one.
Once you are logged in, click Admin in the upper right corner. In the Account Administration area, click on “New Account” and fill out the form
Google Analytics 3 2

When you have completed setting up your account, you will be given the code to place on your site
Google Analytics code

Installing on your site

The ideal place to install the GA Javascript snippet is at the very bottom of your page so that it does not adversely affect your sites performance. The following is the “new” (not really new anymore) method of installing the GA script, I suggest this method.

<code>&lt;script type="text/javascript&gt;
_gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX']); // this is the UA Id that you received in during the Account Setup
_gaq.push(['_trackPageview']); // fires off the initial tracking pixel

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

&lt;/script&gt;</code>

That’s it. For the basic functionality of Google Analytics (which is anything but basic), this is all you need to do. For those of you who need additional functionality such as:

  • Tracking across domains/subdomains (shop.foo.com, blog.foo.com, foo-sister-site.com)
  • Custom Variables
  • JavaScript event tracking (time on site, scroll level, errors, etc.)

please read on.

Tracking Across Subdomains

Because you must specify the domain name for your website when you add it in GA (e.g. www.example.com or example.com), GA ties the cookie for your users to that domain; therefore, if you direct your users to shop.example.com and haven’t explicitly told GA to do so, it will see that as a new user. We can remedy this issue using the _setDomainName method:

<code>&lt;script type="text/javascript&gt;
// CAVEAT: you MUST set domain name prior to calling _trackPageview
_gaq.push(['_setAccount', 'UA-XXXXXXXX']);
_gaq.push(['_setDomainName', '.example.com']);
_gaq.push(['_trackPageview']);
&lt;/script&gt;</code>

It’s very important to note that the domain I set was ‘(DOT)example.com’, the leading dot will force the cookie to be valid across all subdomains of your domain.

The order in which you push items onto the _gaq stack is VERY important, please make sure you read the CAVEATs

Tracking Custom Variables

Custom variables are an extremely powerful way of tying useful data to your users and the pages of your site. Want to know what split tests users in Europe are seeing? How about the states in the US that have the most logged in users? Custom variables are the way to gather such insight. As a user of the free GA service, you will have the ability to create 10 custom variables so use them sparingly.

<code>&lt;script type="text/javascript&gt;
// CAVEAT: just like with setDomainName, you MUST set custom variables prior to calling _trackPageview, otherwise bounced users will not have the custom vars
_gaq.push(['_setAccount', 'UA-XXXXXXXX']);
_gaq.push(['_setDomainName', '.example.com']);
_gaq.push(['_setCustomVar', 1, 'logged_in', true, 1]);
_gaq.push(['_trackPageview']);
&lt;/script&gt;</code>

You can find these reports under: Standard Reporting > Audience > Custom > Custom Variables

Tracking Custom Events

Before we get to that and for the sake of your data, PLEASE READ:

The way bounce rate is calculated in GA is the percentage of users who only had one event fire for them during their visit to your website (_trackPageview, to be specific). If you call trackEvent without manually setting the last parameter to true, the event will be seen as an “interaction event”, and therefore will (possibly unintentionally) decrease your bounce rate; by setting it to true, we are instructing GA to not use the event as a factor in our bounce rate calculation.

About Custom Events

Custom Events are interactive and non-interactive events that GA doesn’t track automatically*, such as scrolling, time on site, button clicks that don’t cause the user to navigate away from the page, ajax calls, etc., etc.

We can use the _trackEvent method to cause GA to fire off the tracking pixel when desired and that is what I will provide a few examples of.

Syntax

<code>&lt;script type="text/javascript&gt;
_gaq.push(['_trackEvent', CATEGORY, ACTION, LABEL, VALUE, OPT_NONINTERACTION]);
&lt;/script&gt;</code>

Time on Page

<code>&lt;script type="text/javascript&gt;
var secondsElapsedToTrack = 15;

setTimeout(function(){
	_gaq.push(['_trackEvent', 'Time', secondsElapsedToTrack+'seconds', secondsElapsedToTrack, null, true]);
}, (secondsElapsedToTrack * 1000));

&lt;/script&gt;</code>

In this example I am tracking users who have been on a page for at least 15 seconds in a category called ‘Time’, I could have a number of these fire at different times, or instead use setInterval to track every 15 seconds (just be careful you turn it off after 3 or 4 so you aren’t blowing out your data limits).

jQuery AJAX Requests

<code>&lt;script type="text/javascript&gt;
$.ajaxSuccess(function(response){
	_gaq.push(['_trackEvent', 'AJAX', response.url, response.responseCode, null, true]);
});
&lt;/script&gt;</code>

Here I’m tracking all jQuery AJAX requests into an “AJAX” category, setting the action to the url that I requested from and giving it a label of the response code so I can see the success rates of urls; I opted not to send a value as I’m not really aggregating anything on the page into this category. The last value I pass (true) declares the event as non-interaction.

Button Click

Given an HTML setup like the following:

<code>&lt;div class="product"&gt;
	&lt;img src="/products/socks.jpg" /&gt;
	&lt;select class="quantity"&gt;
		&lt;option&gt;1&lt;/option&gt;
		&lt;option&gt;2&lt;/option&gt;
		&lt;option&gt;3&lt;/option&gt;
	&lt;/select&gt;
	&lt;button class="addToCart"&gt;Socks&lt;/button&gt;
&lt;/div&gt;
</code>
<code>&lt;script type="text/javascript&gt;
var buttns = document.getElementsByClassName('addToCart'),
    i = 0;
for( i; i &lt; buttns.length; i++){
    buttns[i].onclick = function(){
        var itemName = (this.value || this.textContent || this.innerText || 'unknown_value'),
		quantity = this.parentNode.children[1].value;
	_gaq.push(['_trackEvent', 'Cart', 'AddItem', itemName, quantity]);
    }
}
&lt;/script&gt;</code>

Here I am setting up an interactive event of a user adding something to their cart, the event is going into the ‘Cart’ category, I’m giving it an action of ‘AddItem’, I’m setting the label to the item name and the value to the quantity the user added to their cart. I’m using the default value of non-interaction (false) because this is indeed an interaction.

Scrolled to 90%

<code>&lt;script type="text/javascript&gt;
$(window).scroll(function() {
	if (typeof window.alreadyScrollTracked != 'undefined')
		return;

	var bottom = $(window).height() + $(window).scrollTop()
	,	height = $(document).height()
	,	percentage = Math.round(100*bottom/height);

	if(percentage > 90) {
		window.alreadyScrollTracked = true;
		var message = 'Scrolled to 90%'
		,	scr_params = ['_trackEvent', 'Content Engagement', message, document.location.pathname, null, true];
		_gaq.push(scr_params);
	}
});
&lt;/script&gt;</code>

Outbound Links

<code>&lt;a href="http://www.example.com/foo" onclick="return track(this);"&gt;Example Foo&lt;/a&gt;</code>
<code>&lt;script type="text/javascript&gt;
var track = function(item){
    if(item.href.indexOf(location.host) === -1){
        var hostname = item.href.split('/')[2].split('.').slice(-2).join('.'),
            params = ['_trackEvent', 'Outbound', hostname, item.href],
            _gaq = [];
        
        _gaq.push(params);

        setTimeout(function(){
            location.href = item.href;
        }, 100);
        return false;
    }
    return true;
}
&lt;/script&gt;</code>

Troubleshooting

There are a few solid methods for debugging that I’ve found, you can use any or all of them to track down problems:

  • Centralize your calls to _gaq.push so you can have a debugging mode that logs your parameters to console
    <code>&lt;script type="text/javascript&gt;
    var track = function(params){
    	params = params || [];
    	window._gaq.push(params);
    	if(debugging_flag){
    		console && console.log(params);
    	}
    }
    &lt;/script&gt;</code>
    

  • Use Google Analytics debugging script “u/ga_debug.js”, rather than “/ga.js” (Note: don’t use this script in production as it will slow things down). This will give you so much useful data, including reasons why your data is not being tracked (i.e. GA was expecting a string and you used an integer)
    <code>&lt;script type="text/javascript&gt;
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == window.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/u/ga_debug.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
    &lt;/script&gt;</code>
    
  • Watch the network tab of your browser’s console (Firebug in Firefox) and make sure _utm.gif is being requested every time you have an event fire, if you don’t see that gif in the network tab, your data is NOT being tracked

Happy to answer any questions you have in the comments

Leave a Reply