
Google Analytics for developers - yashke
http://blog.arkency.com/2012/12/google-analytics-for-developers/
======
kevinconroy
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.

~~~
gulbrandr
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...](https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._trackPageLoadTime)

~~~
kevinconroy
Thank you! I was unaware of this change.

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

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

~~~
iamchrisle
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.

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

------
stephth
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...](https://www.google.com/search?q=site:https://developers.google.com/analytics/devguides/collection/ios/v2/%20offline)

[2] [http://stackoverflow.com/questions/6618719/how-does-
google-a...](http://stackoverflow.com/questions/6618719/how-does-google-
analytics-for-android-handle-offline-app-usage)

[3] [http://stackoverflow.com/questions/4484748/what-happens-
with...](http://stackoverflow.com/questions/4484748/what-happens-with-iphone-
google-analytics-calls-when-theres-no-internet-connect)

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

~~~
campnic
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...](https://developers.google.com/analytics/devguides/collection/android/v2/dispatch)

~~~
stephth
_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).

------
bluetidepro
> _"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! :)

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

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

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

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

------
jgalt212
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&...](http://support.Google.com/analytics/bin/answer.py?hl=en&answer=1136920)

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

~~~
simonw
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?

------
iamchrisle
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...](http://cutroni.com/blog/2012/02/21/advanced-content-tracking-
with-google-analytics-part-1/))

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.

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

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

~~~
iamchrisle
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&...](http://support.google.com/analytics/bin/answer.py?hl=en&answer=1205784))

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

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

------
dudus
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.)

~~~
ApolloRising
This is really impressive.

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

~~~
iamchrisle
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.

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

~~~
polyfractal
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.

