Adding Google Analytics to your web pages dynamically
Single-script Google Analytics inclusion
Posted on Friday, December 7th, 2007 at 12:35 pm
I’ve just started using and it f*cking rocks. It’s simply amazing the amount of information it provides, but more amazing still is the way it shows you how people are using your site.
Installation is as easy as copy and pasting two scripts into each web page you want tracked. What could be easier than that!? Well, how about one script?
Here’s the code needed to run the tracking functions automatically:
Here’s the code to load the tracking functions without running them (works in ALL browsers, not just IE!) so you can call the code yourself later (for example, tracking an AJAX call):
Of course, there’s a few of these out there already, but here’s the specifics on my take:
- easy: a single external script that loads the Google code dynamically
- intelligent: calls tracking function only when remote script has fully downloaded
- versatile: use of defer attribute to run automatically (or not)
- customizable: provides a wrapper function to execute your own custom code
- tidy: intermediate setup variables are created privately via a function closure
Just be sure to add your tracking id to the initialization function!
Download google-analytics.js