Home » Code: JavaScript page tagging

Code: JavaScript page tagging

Chapter 10 – Website Optimization Metrics

To install Google Analytics, a developer need only include this bit of code on every page in the site by means of a site-wide footer:

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

Unlike with log analysis tools, you can also track JavaScript or Flash events caused by widgets that don’t necessarily call the server. In Google Analytics, you can do this through the trackPageview function.

Say we want to count a page view every time a user clicks the Next button in a photo gallery without refreshing the page. We could write the following bit of JavaScript:

<input type="button" onclick="getNextPhoto(); pageTracker._trackPageview('/photogallery/
next/');" value="Next" />

Now when users interact with our photo gallery, even though the page does not fully refresh, we will record a page view. You can find more instructions on this level of tagging at http://www.google.com/support/googleanalytics/bin/answer.py?answer=55597&topic=10981.