Introduction to ga.js (Legacy)

ga.js is a JavaScript library for measuring how users interact with your website. This is a legacy library. If you are getting started with Google Analytics you should use the latest tracking library, analytics.js.

Tracking Code Quickstart

The Analytics snippet is a small piece of JavaScript code that you paste into your pages. It activates Google Analytics tracking by inserting ga.js into the page. To use this on your pages, copy the code snippet below, replacing UA-XXXXX-X with your web property ID. Paste this snippet into your website template page so that it appears before the closing </head> tag.

If you need to do more than basic page tracking, see the tracking reference for a list of methods available in the API and see the Usage Guide for details on using the asynchronous syntax. For step-by-step instructions on setting up tracking, see the Help Center article on setting up tracking.

<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>

The snippet above represents the minimum configuration needed to track a page asynchronously. It uses _setAccount to set the page's web property ID and then calls _trackPageview to send the tracking data back to the Google Analytics servers.

Important: If you are updating your pages from the traditional snippet to the latest, asynchronous version, you should remove the existing tracking snippet first. We do not recommend using both snippets together on the same page. For migration instructions, see Migrating to Async.

How the Asynchronous Syntax Works

The _gaq object is what makes the asynchronous syntax possible. It acts as a queue, which is a first-in,first-out data structure that collects API calls until ga.js is ready to execute them. To add something to the queue, use the _gaq.push method.

To push an API call onto the queue, you must convert it from the traditional JavaScript syntax into a command array. Command arrays are simply JavaScript arrays that conform to a certain format. The first element in a command array is the name of the tracker object method you want to call. It must be a string. The rest of the elements are the arguments you want to pass to the tracker object method. These can be any JavaScript value.

The following code calls _trackPageview() using the traditional syntax:

var pageTracker = _gat._getTracker('UA-XXXXX-X');
pageTracker._trackPageview();

The equivalent code in the asynchronous syntax requires two calls to _gaq.push.

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

In the asynchronous syntax, the creation of the tracker object is implied, but we still need a way to set the web property ID for the tracker. The _setAccount method has been added to provide this capability. All the other tracker object methods are the same in both asynchronous and traditional tracking. Only the syntax is different.

For more information on the asynchronous syntax, see the Tracking Reference for the _gaq.push method.

Back to Top

Tracking with HTML Event Handlers

The asynchronous tracking syntax should also be used from within DOM event handlers. For example, the following button generates an event when it is clicked.

<button onclick="_gaq.push(['_trackEvent', 'button3', 'clicked'])"></button>

Even if this button is clicked before the browser has finished loading ga.js, the event will be captured and eventually executed. Using traditional tracking, the browser might throw an exception in this situation.

Back to Top

Pushing Functions onto the Queue

In addition to command arrays, you can also push function objects onto the _gaq queue. The functions can contain any arbitrary JavaScript and like command arrays, they are executed in the order in which they are pushed onto _gaq. This technique is useful for calling the tracking APIs that return values. For example, the following code builds a linker URL and sets the href property for a link with the result.

_gaq.push(function() {
  var pageTracker = _gat._getTracker('UA-XXXXX-X');
  var link = document.getElementById('my-link-id');
  link.href = pageTracker._getLinkerUrl('http://example.com/');
});

The example above uses _gat to create a tracker object, but because it is assigned to a local variable, code outside of the function cannot use it. While this is acceptable, you can use the _gat._createTracker method to create a permanent, globally accessible object. The following code demonstrates how this would work.

_gaq.push(function() {
  var pageTracker = _gat._createTracker('UA-XXXXX-X', 'myTracker');
  var link = document.getElementById('my-link-id');
  link.href = pageTracker._getLinkerUrl('http://example.com/');
});

_gaq.push(['myTracker._trackPageview']);

The example above creates an asynchronous tracker inside the function and then references it later by name in the command array.

The opposite use case is also possible. For example, if you need to use an asynchronous tracker object created via a previously pushed command array, use the _gat._getTrackerByName method. The following code demonstrates how it works.

_gaq.push(['myTracker._setAccount', 'UA-XXXXX-X']);

_gaq.push(function() {
  var pageTracker = _gat._getTrackerByName('myTracker');
  var link = document.getElementById('my-link-id');
  link.href = pageTracker._getLinkerUrl('http://example.com/');
});

Back to Top

One Push, Multiple Commands

Instead of typing _gaq.push(...) for each call, you can push all of your commands at once. The following code demonstrates this technique.

_gaq.push(
  ['_setAccount', 'UA-XXXXX-X'],
  ['_setDomainName', 'example.com'],
  ['_setCustomVar', 1, 'Section', 'Life & Style', 3],
  ['_trackPageview']
);

This works because the _gaq.push method imitates the Array.push method, which allows pushing multiple items with one invocation.

Back to Top

Splitting the Snippet

If you prefer to put the Analytics snippet at the bottom of the page, you should know that you don't have to put the whole snippet at the bottom. You can still keep most of the benefits of asynchronous loading by splitting the snippet in half—keep the first half at the top of the page and move the rest to the bottom. Because the first part of the tracking snippet has little to no effect on page rendering, you can leave that part at the top and put the part of the snippet that inserts ga.js at the bottom.

A page with the asynchronous snippet split in half might look like this:

<html>

<head>
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_trackPageview']);
  </script>
</head>

<body>
  <p>Page Content</p>

  <script src="some_random_script.js"></script>

  <p>Page Content</p>

  <script type="text/javascript">  (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> </body> </html>

Both pieces of code need to be wrapped in their own script tags, but only the last six lines of the original asynchronous snippet need to be moved to the bottom. All the lines that push methods onto _gaq can stay at the top.

Back to Top

Avoiding Common Pitfalls

When using either the asynchronous or traditional syntax, keep in mind the following:

  • Method names are case-sensitive.
    If you use a method name without the proper casing, your method calls will not work. Examples:
    _gaq.push(['_trackpageview']);   // bad
    _gaq.push(['_trackPageview']);   // good
  • Use the correct method names.
    If your tracking is not working correctly, check to make sure you are using the correct name for the method. Examples:
    _gaq.push(['_setDomain', 'example.com']);       // bad
    _gaq.push(['_setDomainName', 'example.com']);   // good
    
  • Only strings should be passed in with quotes. All other types should be left unquoted.
    Any value that is not a string, such as a booleans, object literals, functions or arrays, should be passed in without quotation marks. Use only quotation marks when you are passing in something that is meant to be interpreted as a string. If you are migrating from the traditional syntax, any function parameter that was passed in without quotation marks should remain unquoted in the asynchronous syntax. Examples:
    _gaq.push(['_setAllowLinker', 'false']);    // bad
    _gaq.push(['_setAllowLinker', false]);      // good
    
  • Make sure that strings do not contain leading or trailing whitespace.
    Examples:
    _gaq.push(['_setAccount', ' UA-65432-1']);    // bad
    _gaq.push(['_setAccount', 'UA-65432-1']);     // good
    

Back to Top

Disabling Tracking

In some cases, it may be necessary to disable the Google Analytics tracking code on a page without having to remove the code snippet. For example, you might do this if your site's privacy policy includes the ability for a visitor to opt-out of Google Analytics tracking.

The ga.js tracking snippet now includes a window property that, when set to true, disables the tracking snippet from sending data to Google Analytics. When Google Analytics attempts to set a cookie or send data back to the Google Analytics servers, it will check for whether this property is set to true. If it is, it will have the same effect as if the visitor had the Google Analytics Opt-out Browser Plugin installed.

To disable tracking, set the following window property to true:

window['ga-disable-UA-XXXXXX-Y'] = true;

Where the value UA-XXXXXX-Y corresponds to the web property ID on which you would like to disable tracking.

This window property must be set before the tracking code is called. This property must be set on each page where you want to disable Google Analytics tracking. If the property is not set or set to false then the tracking will work as usual.

So, for example, if your Google Analytics tracking code on a page includes:

_gaq.push['_setAccount', 'UA-123456-1']

And you would like to disable that tracking code from setting cookies or sending data back to Google Analytics, then you use the following code before the tracking code is called:

window['ga-disable-UA-123456-1'] = true;

If you use multiple trackers on a page with multiple web property IDs, you must set the equivalent window['ga-disable-UA-XXXXXX-Y'] variable to true for each web property to completely disable Google Analytics tracking on that page.

Example

Here's a simple example of some code you can use to provide opt-out functionality for your users.

First, add a new HTML link to your site to execute the opt-out logic:

<a href="javascript:gaOptout()">Click here to opt-out of Google Analytics</a>

Then add the following snippet of code before the ga.js code snippet. Make sure to replace the value of gaProperty from UA-XXXX-Y to the property used on your site. This is the same value that you pass to the _setAccount command.

<script>
// Set to the same value as the web property used on the site
var gaProperty = 'UA-XXXX-Y';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
}
</script>

When a user clicks the opt-out HTML link, the custom gaOptout function will execute. It will set a cookie for a long time in the future and disable analytics.js data collection. When a user returns to this site, the script above will check to see if the opt-out cookie has been set. If it has, then the analytics.js data collection will also be disabled.

Forcing SSL (HTTPS)

To force Google Analytics to always send data using SSL, even from insecure pages (HTTP), use the _gat._forceSSL method, as in this example:

_gaq.push(['_setAccount', 'UA-12345-1']);
_gaq.push(['_gat._forceSSL']);       // Send all hits using SSL, even from insecure (HTTP) pages.
_gaq.push(['_trackPageview']);

Back to Top