3 Ways to Track Web Pages with Google Analytics

Post #739 categorized as Function, last updated on Jan 24, 2010
Tagged with ajax, analytics, code, google, javascript, statistics

[ Google Analytics ] Many bloggers, designers, and developers take advantage of Google’s free Analytics service to track and monitor their site’s statistics. Along with a Google account, all that’s needed to use Google Analytics is the addition of a small slice of JavaScript into your web pages. For a long time, there was only one way of doing this, and then in 2007 Google improved their GATC code and established a new way for including it in your web pages. Many people switched over to the newer optimized method, but may not realize that there are now three different ways to track your pages with Google Analytics. The latest method uses asynchronous tracking to minimize negative impact on user experience. Let’s take a look at each of these three methods for tracking your web pages with Google Analytics..

Method 1: Old School – Tracking sites with urchin.js

Web-design veterans are well familiar with the original, old-school method of GATC inclusion via the urchin.js code:

<script type="text/javascript">
_uacct = "UA-XXXXX-X";
urchinTracker();
</script>

Ahh yes, those were the days.. This method worked great for years, and continues to work just fine to this very day. Although I personally would recommend using one of the newer methods of including the GATC, you may still use this old-school method by simply copying and pasting the code into the bottom of your web pages, preferably before the closing <body> element. And then don’t forget to edit the “UA-XXXXX-X” string to match your actual GA ID.

So that’s pretty boring — let’s check out something a little newer..

Method 2: New School – Tracking sites with ga.js

In late 2007 – after years of using the original urchin.js script – Google updated and improved the GATC and renamed the tracking file to “ga.js”. As of now, this new tracking code is the platform on which all new Google Analytics features are deployed.

Here are some of the benefits of using the new ga.js tracking script:

  • Smaller file size
  • Improved performance
  • Object-oriented programming conventions
  • Namespacing and improved readability
  • Easy JavaScript integration

As with the old urchin.js-based method, using this new method requires inclusion of a small snippet of tracking code on your web pages. Depending on how you deliver your pages — over HTTP, SSL, or a combination of both — the code used to include the new Google Analytics tracking code will vary:

All web pages delivered via standard HTTP protocol

<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXX-X");
pageTracker._trackPageview();
</script>

All web pages delivered via secure HTTP (SSL)

<script src="https://ssl.google-analytics.com/ga.js" type="text/javascript"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXX-X");
pageTracker._trackPageview();
</script>

Web pages delivered via combination of standard and secure protocols

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script>

As you can see, each of these methods consists of two parts: the first references the ga.js tracking code and the second executes it. A couple of notes on proper/recommended usage of either of these methods:

  • Do not combine different tracking scripts on the same page
  • Inlcude the tracking code after before the closing <body> element at the bottom of your web pages
  • Do not combine the ga.js method with the old urchin.js method
  • Don’t forget to edit the “UA-XXXXX-X” string to match your actual GA ID

I think this is the GA-inclusion method that most bloggers and designers are using in their pages. But even so, there is yet another way of including the tracking code that improves the user-experience for your visitors..

Method 3: Asynchronous Tracking – Better tracking with ga.js

This newer method of GA tracking uses a slice of asynchronous JavaScript to optimize the way in which browsers load the ga.js tracking script. The asynchronous tracking method improves the user experience and allows inclusion of the tracking script closer to the beginning of the web page without delaying subsequent content from rendering. As you might suspect, the asynchronous tracking method requires a slightly more complex inclusion method:

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

This code represents the minimum configuration required to track a page asynchronously using Google Analytics. To take advantage of this method, you can use this tracking script on your pages by following the simple steps below. To go beyond the basics, check the official tracking reference and usage guide for information on the GA API and proper asynchronous syntax.

How to setup asynchronous analytics tracking on your site

  1. Important: Remove any existing ga.js tracking code, if present 1
  2. Insert the asynchronous snippet before the closing </head> element after the opening <body> tag 2
  3. Edit the “UA-XXXXX-X” string to match your specific web-property ID
  4. Add any customizations using the GA API and asynchronous syntax

That’s all there is to getting asynchronous GA tracking setup on your site. Of course, there are a few important notes that you should keep in mind:

  • If you experience content-loading issues, move the tracking code to the bottom of the page
  • 1 Asynchronous tracking is not available with the old urchin.js-based method.
  • 2 The optimal place for the tracking snippet is after the last <script> element in the <head> section Edit: “While it is customary to place JavaScript code in the <head> section, placing the asynchronous snippet there may trigger a parsing bug in Internet Explorer 6 and 7 on some pages. The easiest solution to this problem is to place it at the top of the <body> section.” – Google Analytics Asynchronous Tracking
  • Do not use more than one tracking snippet on any given page — you’ll break stuff

Subscribe to Perishable Press


26 Responses

TopLeave a comment

[ Gravatar Icon ]

#1JP

Google indicates that the new Asynchronous tracker should be placed at the top of the tag and not in the section.(I found out about this a few days ago as I also read on the google analytics site that the new tracker should be placed in the section>.

http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html

[ Gravatar Icon ]

#2brian kuhn

A couple minor errors here:
The traditional ga.js snippet (Option #2) should go before the closing BODY tag.

The async snippet (Option #3) should go after the opening body tag.

To avoid confusion, I’d really appreciate if you update your (very nice) guide.

[ Gravatar Icon ]

#3Jeff Starr

Article updated with the correct information – thank you JP and brian :)

[ Gravatar Icon ]

#4Wulf

Great article, Jeff; I didn’t know GA could track async transactions now; many thanks.

[ Gravatar Icon ]

#5SohoInteractive

I was also unaware of this. Many thanks.
Now have to update GA code on many websites.

[ Gravatar Icon ]

#6Jeff Starr

My pleasure, Wulf and SohoInteractive — thanks for the feedback :)

[ Gravatar Icon ]

#7JP

@Wulf: someone’s abusing the semi-colon! Did you read Oatmeal’s “How to use a semi-colon” comic too? haha

[ Gravatar Icon ]

#8Trav

This is a great heads-up Jeff, many thanks. Have you tried the new method, and what did you observe insofar as load times relative to previous versions? It’s definitely bothered me in the past when the GA script held up my page-load.

[ Gravatar Icon ]

#9Teddy

Thank you Jeff for sharing your insights on Google Analytics tracking. The only method I have used is the old school method because shortly after that, I started using a WP plugin for Google Analytics that pretty much keeps a lazy user’s hands off hardcoding anything into the theme files.

However, in a recent effort to reduce server and CPU load, I have been cutting down on the number of WP plugins I’m running but I was still totally clueless on getting GA to work without a WP plugin. Your tutorial is such a life saver, thank you!

Have a lovely Sunday and a great week ahead!

[ Gravatar Icon ]

#10Jeff Starr

@Trav: yes, it took a bit more time to get it setup and working, but the performance boost was definitely visible on my test site. I would say definitely worth checking out. There may already be a WordPress plugin for it, but I haven’t searched yet.

@Teddy: absolutely my pleasure — glad if it will help. I think it’s good to have all three GA techniques summarized for easy reference. I still run the old urchin.js method on a few sites, but newer sites get the ga.js treatment. Also, on some of my personal sites (such as this one), I don’t use GA at all, preferring the more closely integrated Mint to keep an eye on things.

[ Gravatar Icon ]

#11puci

Very helpful! Many thanks…

[ Gravatar Icon ]

#12Al Kamal Md. Razib

Thanks for sharing this type of important information.

[ Gravatar Icon ]

#13Patricia

Hello Jeff,
I use the gaJs code. Since I use SSI, the Analytics code is in the footer html file - and all the webpages have an include to it. Everything works great with Analytics. However, the gaJs code has two JS calls (Firebug Page Speed is always nagging me about this.)

Anyway, this newer code looks like it might be one JS call? (My expertise is NOT in JS), but I do work on making sure my pages load as quickly as possible. But since my current code is in the footer and loading last anyway, could I put this new code in the footer? Is there much of a benefit to me using the new code? Appreciate your thoughts.

Very nice site. Thanks!

[ Gravatar Icon ]

#14Jeff Starr

@Patricia: Yes, it should be just a single call, if I understand the question correctly. If you use it, you want to make sure to remove your current tracking snippet because you don’t want to use more than one tracking snippet on any given page. Also, if you use the new code, you need to include it after the opening <body> tag instead of in the footer. As for benefits, I think they’re mostly aimed at your visitors, who should enjoy a (slightly) better experience at your site with the new code in place.

[ Gravatar Icon ]

#15Nevin S

Awesome Article!
nice case study,very resourceful,informative and helpful for me,I Really appreciate the information you are offering here.
Thanks for sharing

[ Gravatar Icon ]

#16Akhtar Asghar

For those not wanting to serve cookies on assets(jpg,ico,png,swf etc) in a subdomain you can add this code, replace the xxxx with your analytics code and replace www.mysite.com with your site name.

var _gaq=_gaq||[];_gaq.push(['_setAccount','UA-xxxxxx-xx'],['_setDomainName','www.mysite.com'],['_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);})();

Now if someone can come up with something to kick quantcast on subs that would be grand.

[ Gravatar Icon ]

#17Kamrul Hasan

I am not a very big fan of Google Analytics. Only because I often lost my ways in badly designed navigation of Google Analytics. A simple alternative is statcounter.com. I get every thing I need here.

[ Gravatar Icon ]

#18Bambang Sugiarto

Hi Jeff,

Nice post… By the way, I just modified the Google Analytics plugin for WordPress and added the new asynchronous tracking method… Please review my post about Asynchronous Google Analytics plugin for WordPress at http://www.minilibra.com/wordpress/plugins/analytics.html

Cheers
Bambang Sugiarto

[ Gravatar Icon ]

#19testbeta

thanks to Matt Cutts {or some other source blog or other don’t know} i knew asynchronous js technique but then i think i am still using the older #2 ga.js
Google Analytics have been my favorite tools saw it’s growth from urchin.js to asynchronous it’s a great tool and yours is a nice write up how can you write things so clearly!!!!!

[ Gravatar Icon ]

#20Mathias Bynens

Let’s add a fourth way to the list: using an optimized version of the asynchronous Analytics snippet. I describe some possible optimizations in this article: Optimizing the asynchronous Google Analytics snippet.

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.