Hacker News new | past | comments | ask | show | jobs | submit login
Google Analytics for developers (arkency.com)
95 points by yashke on Dec 5, 2012 | hide | past | favorite | 43 comments



Here are two of my favorite tricks. You can do this just after you set your account ID:

        <!-- Async Tracking Code - http://code.google.com/intl/en-US/apis/analytics/docs/tracking/asyncTracking.html -->
	<script type="text/javascript">
	  var _gaq = _gaq || [];
	  _gaq.push(['_setAccount', 'YOUR ANALYTICS ID GOES HERE']);
	  _gaq.push(['_trackPageview']);

          //*******************
          // Trick #1: Track page load time in Google Analytics
          // (note: only works for HTML5 browsers)
          //*******************
	  _gaq.push(['_trackPageLoadTime']);

	  (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);
	  })();
	  
          //*******************
          // Trick #2: Add a Javascript error handler so that it creates an event in Google Analytics
          // whenever there's a CLIENT-SIDE javascript error
          //*******************
	  window.onerror = function(message, file, line) { 
	     var sFormattedMessage = '[' + file + ' (' + line + ')] ' + message; 
	     _gaq.push(['_trackEvent', 'Errors', 'Browser', sFormattedMessage, null, true]);
	  }
	</script>

Update: Included complete GA code to address any confusion on order and values available in stack.


According to this page [0], _trackPageLoadTime() is deprecated because site speed reporting is enabled automatically for all users.

Update: your 2nd trick is still relevant though

[0] https://developers.google.com/analytics/devguides/collection...


Thank you! I was unaware of this change.


As others have noted, _trackPageLoadTime is depreciated.

However, Google Analytics only automatically samples the page load time for 1% of visitors.

To change this call

_gaq.push([‘_setSiteSpeedSampleRate’, 100]);

before tracking the pageview. This will sample 100% of users for the site load time.

https://developers.google.com/analytics/devguides/collection...


Very good point! Just be careful...

- Google will take a lot longer to report your data if you do this. - Google also has data limits. If you're experiencing 10k+ pageviews a day, you will probably run into the limit and it will stop reporting stuff.

http://support.google.com/analytics/bin/answer.py?hl=en&...


You should consider including a userid of some sort with the error reporting. It can let you debug down esoteric, hard to reproduce errors reported by users, which are otherwise almost impossible.


_trackPageLoadTime is deprecated. It's already enabled by default, so you don't need that line.

Place this stuff in the head tag rather than the bottom. It's async code and placing it closer to the top you can make sure you're setting up tracking the page as soon as possible.


> "// Track page load time in Google Analytics"

After adding that, where does that appear in the Google Analytics dashboard? Can you explain further how that works? Thanks!


It's under Standard Reporting -> Content -> Site Speed

The GA code will track client side page load time (DOM fully loaded) across your site. You'll get site-wide averages and you'll also get to drill in on slow pages. This doesn't work for every single browser (last I checked it only worked for browsers that support HTML5), but it still provides a good sample size.

It's also important to do this as Google Webmaster tools dropped support of the Site Speed lab which shows you how fast Google thinks your site is ( <1.5 seconds user DOM load is considered faster, >= 1.5 seconds is "slow"). If you're trying to improve your Google ranking you need to be tracking how fast Google thinks your site is. (Also, fast websites are great for lots of reasons, not just Google ranking.)

See also: http://analytics.blogspot.com/2011/05/measure-page-load-time...


In my experience Google's measures are 1-2 seconds higher than what I personally experience. Not sure why. Take it with a grain of salt and look for trends.

Googlebot seems to give up crawling your site after about 14 seconds :) You might see that reported in GWT.


There are a lot of reasons this may be. Your Internet may be faster than your average user's. You may be closer geographically to your server. Different browsers will show different load speeds. The site may be cached for you most of the time.

I know you weren't actually asking, but I figured it's worth stating this for someone else who might experience the same thing. Load times do vary greatly. Digging down into the Analytics can show you where/why they vary. And as you said and as always with Analytics, look for trends more than exact figures.


+1000 I'll tend to look at the speed coming off the server instead. At least I know that I can control 100%. If the user is on a dial up modem, not my problem ;)


There are many things you can do to improve the performance of your website, even to people with dial up - or worse - Mobile!

Compress data with gzip is probably the big one for modem users, but also batching scripts and CSS together, reducing image sizes, re-arranging code to reduce blocking during rendering.

These are all things under your control, and with current mobile browsers, these are things you really must care about


Getting user perceived page load time down is vital for most sites. You'll see your bounce rate drop, pages per visit rise, and conversion rates go up. A better experience for your users is always better for you.

You can do something to make like better for those on mobile and dialup with server settings, image compression, and the like. You can't change their connection speed, but you can focus on their experience.


Best to check for the existence of _gaq before pushing elements into it, or the user might get a reference error.


I just updated by code segment to show where I call this (it's right after declaring _gaq).


I'm a big fan of the GAS (Google Analytics on Steroids) wrapper [1]. One of the coolest features is firing GA events from embedded YouTube videos [2] to track viewer retention [3].

[1] https://github.com/cardinalpath/gas

[2] https://gist.github.com/2715896

[3] http://i.imgur.com/QILnG.png


I was expecting something different with the "for developers" title. Perhaps replicating some of the features of MixPanel or KissMetrics, which can track all kinds of interesting things for developers -- which features users of your app use most, in which order they use those features, whether this week's signups are more engaged than last week's signups, etc.


I actually use event tracking a lot to track exactly that. For our clients, we not only know which features they're using most but by tracking validation errors in Google Analytics we also know what parts of the app is giving users trouble.

Best part is, with Google Analytics you can see what people did before and after they ran into trouble and correct for the user experience.


This. We recently started doing this and the data it's provided has been awesome.


That's the next topic I want to digg in playing with Google Analytics. When I have some results I'll post them.


This is awesome. Thanks!!


Is anyone using GA to track mobile apps? The mobile SDKs shows a lot of potential until you start wondering about offline usage, GA being a website tracker first. I couldn't find any final answers but from what I can see it might be a sore point: the SDK docs dodge the topic [1] and I see complaints, ie events can be batched for later but get the timestamps of when they were uploaded, instead of when they happened [2,3,4].

[1] https://www.google.com/search?q=site:https://developers.goog...

[2] http://stackoverflow.com/questions/6618719/how-does-google-a...

[3] http://stackoverflow.com/questions/4484748/what-happens-with...

[4] http://productforums.google.com/forum/#!msg/analytics/132Eet...


We are using GA to track mobile apps. The local queuing and dispatch of hits to GA is covered here[1]. We've found it to be pretty reliable. You can also modify the dispatch time for testing, etc.

[1]https://developers.google.com/analytics/devguides/collection...


Note: Data must be dispatched and received by 4 a.m. of the following day, in the local timezone of each profile. Any data received later than that will not appear in reports.

Do your mobile apps require an Internet connection? From what I'm seeing I imagine that's a prerequisite to use GA. It's a deal breaker for me though, I can't intentionally throw away a slice of offline usage data (iPods, iPads, etc).


> "You probably use most of basic features of Google Analytics - you know how to get information how many visits was made each day, you know your users browser segmentation etc. But how can you measure effects of your blog post?"

That hits the nail on the head. Great article, although I wish you went into it a bit more in depth on how to do those actions, how to do other actions, and then maybe talk more about the benefits.

I love browsing Google Analytics but I will be the first to tell you that I don't really understand much from it, other than than the obvious things. I really wish I could figure out how to integrate it better with my web sites, like you quickly demoed. Again, I really suggest doing this same article with a bit more information. It would really help out those who are your target audience for this article. Thanks! :)


Thanks, as I mentioned in other comment - I plan to digg deeper and share knowledge, so be patient :)


Oh, I must have missed that in the comments. I really appreciate that! Keep me posted, would love to see that article! Thanks! :)


You can also do this on the server side. Here is a Python implementation: https://github.com/kra3/py-ga-mob


This is the Python port of my http://code.google.com/p/php-ga/ project :)


The article is interesting, but gives some bad instructions on how to track outbound links and also probably how to track form submissions. Because of the asynchronous nature of communications back/forth from Google Analytics if you load a new page before an event is properly tracked, you won't be able to see it on the GA Dashboard. Bad intel is worse than no intel at all.

Here's what Google itself has to say on the matter: http://support.Google.com/analytics/bin/answer.py?hl=en&...

Here's how to correct one code example from the blog post:

  //this function is OK, but probably an unnecessary abstraction of a one-liner
  function trackEvent(category, action, label) {
    window._gaq.push(['_trackEvent', category, action, label])
  }

  //this event handler will not track some non-negligible percentage of events
  $("article a").click(function(e) {
    var element = $(this)
    var label = element.attr("href")
    trackEvent("Outbound link", "Click", label)
  });


  //corrected outbound link event handler which gives GA 100 ms to register
  //the event.  higher than 100 risks UX degradation, lower increases the %
  //of untracked events.  100 ms is happy medium  
  $("article a").click(function(e) {
    e.preventDefault();  //stay on the page for now
    var element = $(this)
    var label = element.attr("href")
    trackEvent("Outbound link", "Click", label)
    //leave the page after a short delay
    window.setTimeout("window.location.href='" + label + "'", 100);
  });


I'm a bit suspicous of that method... will it still work for people right clicking and opening in new window, or shift-clicking, or middle-clicking, or right clicking and copying the URL?


If you want to track if people are reading your blog, you can use the onscroll javascript event that fires events into Google Analytics. (eg: http://cutroni.com/blog/2012/02/21/advanced-content-tracking...)

By looking at time to scroll, time to the end of the blog post, and comparing that to the number of unique page views per visit, you can tell if your content is engaging.


Those are some good basics.

Tracking user actions can be very useful: I use it on movieterminals.com to see everything that gets typed into each console. The theory being that (one day?) I'll use that to enhance the scripts to work how people expect.

Tracking an event per page 404 or 500 can also be very helpful. If you aren't already using something more robust to track errors you could even setup alerts to watch for those events and contact you.

Goals are good, although funnels are even better.

Finally: if you can afford it I've found that Clicky offers many great advantages over google analytics. More helpful default reports, a better realtime view, etc.


At the risk of going off topic, a question about sampling and sampling rates. If I set sampling to 1%, will the visitor totals in the Google Analytics dashboards reflect 1% of my true values or do they compensate/extrapolate out to 100% based on the sampling rate?


No.

There are two things here. Sampling rate for calculating page timing and using sampled data when generating reports. Confusingly, they are two different things with the same word "sample."

Sampling rate only affects calculating page timing because it's client side and slows down the client. (http://support.google.com/analytics/bin/answer.py?hl=en&...)

Google Analytics will collect all the unfiltered data for the web property. (http://support.google.com/analytics/bin/answer.py?hl=en&...)

However, to speed up ad-hoc querying, like when you create a custom report, it will limit the amount of data it will fetch to generate that report in order to make the user interface faster.

You can increase/decrease that using the slider. YOu will only see the slider after something like 250k unique pageviews.

Google Analytics Premium increases the number. If you really want to get a better sense of page timing, you should look both at the client side timing and the server side timing together. All you can really control is stuff going out. You can't help it if the user is running a netbook with 512 megs of RAM :)


If you want to extract more data from your site to Google Analytics I recommend GAS (Google Analytics on Steroids).

https://github.com/CardinalPath/gas

It adds these events and even more to your site.

(I'm the main developer by the way.)


This is really impressive.


How can you see individual user sessions using Google Analytics? In other words, how can I see, for an individual visitor, their landing page, sequence of subsequent page views, and finally their exit page?


Generally you should be paying attention to trends, not individual users. Either way:

Landing pages: Go to Content > Site Content > Landing Pages

What you probably want is to create an advanced segment: Landing page = something. You can use regex or an exact match term.

Then go to audience > visitor flow, select the advanced segment you used and you can visually see how users navigated your site.

Remember: Keep in mind that a user can technically visit your site using browser tabs. That would give you a report where people went from page A to page B even if there isn't a link on page A going to page B.

Hence: Use GA to gain insight into trends.


Perhaps I'm confused but what benefit do you get from using event tracking for an outbound click, and lastly what does ET have to do with real time?

Thanks


I use event tracking on my outbound clicks all the time. My side project is a vertical niche search engine, so I like to know when, where and how people are leaving the site (since that is the point of the app afterall).

I have some of it tracked with internal code, but for a lot of things that don't need rigorous analysis/tracking, firing an outbound click event to GA is sufficient.


If gives you more context around an exit to your site, ie someone didn't just hit back or close their browser, they left your site via a means you provided, and this is where they went




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: