Why should you care?

AngularJS and web analytics part 1

Imagine you have a microsite with 10 webpages and each page is tracked with Google Analytics. Then your developers are keen to jump on the AngularJS bandwagon and decide that they will rewrite the microsite using a single template page and 10 HTML fragments. Where do you think the Google Analytics tag will be? There are good chances that the single template will be tagged. Symptoms?:

  1. The page views have dropped suddenly
  2. The bounce rate has increased and reached a new plateau
  3. Only one of the 10 pages gets traffic which explains the higher bounce rate
  4. Traffic from search engines might be down by a lot. If your website traffic comes from mostly search engines you might interpret that as the cause of your reduced traffic, which is wrong. A site that sits on page 10 of the search engine results pages would have the drop in page views just the same
  5. Total time spent per visit on the single page that your visitors now see increases to almost the same as the total time spent on the whole microsite per visit before the change, just a little lower though

It could feel like your traffic is behaving as is your microsite has suddenly become a blog. A single page gets all the traffic, high bounce rate but decent time spent per visit.

Once you find out what happened your developers should have put the analytics tags in the HTML fragments that load. AngularJS will not permit script blocks in the HTML fragments. There's a window.onhashchange Javascript event but your microsite might not show the hash in the URL. AngularJS hi-jacks that event for its own purposes so that won't work either anyway. One way to get analytics to work is the AngularJS controllers. For each HTML fragment that could get injected onto the page there's a Javascript function and the contents will execute in response to the injection of that fragment. That's where you could put your Google Analytics tag or any analytics tag. You could also trigger your virtual page views in response to clicks on the navigation links.

At that point you might notice that your first page view gets double-counted. That's because have a master page and a HTML fragment which loads by default. Each have an analytics tag that fires a page view request. Just don't tag the master page in that case. Only tag the master page if no default HTML fragments gets injected on to the page. The same thing applies to iframes basically.

If you opted for triggering the virtual page views in response to clicks on the navigation links your event handlers will need to be declared at the bottom of the master page HTML. You will not need to add analytics code in the controller functions in that scenario.

Other AngularJS articles

Code examples