Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring Page Load Time of single-page app with GA

I'm using Google Analytics in an SPA. For any virtual page redirects (like an AJAX call to refresh the body of the page), I'm getting a page load time of 0ms. Is there a way to track how long that takes, just as if it was a full page refresh? I'm hoping to include how long it takes for the AJAX call and also the time to download and display images that are loaded as a result.

like image 691
skb Avatar asked May 21 '17 04:05

skb


1 Answers

As you have found, Google Analytics will not provide page timings for SPA's. This includes if you increase the site speed sample rate to 100. This is because Google Analytics calculate the page timings using the Navigation Timing API.

For example, DOM loaded would be:

$(document).ready(console.log((Date.now() - 
    performance.timing.domComplete)/1000))

To over come this problem, you will need to use custom metrics. The solution has three steps.

1) Set up a custom metric in GA.

Go to Admin > Property > Custom Definitions > Custom Metric.

Create a new Custom Metric, with the scope of Hit and the formatting type of time. Note: Specify time in seconds, but it appears as hh:mm:ss in your reports.

2) Set up a timer.

You will need to capture the time when you want to start the measurement of page load time.

An example solution to this might be by decorating all of your internal links, e.g:

$('a[href*="stackoverflow"]').click(function(){
  time1 = Date.now()
})

3) Send the time eclipsed (in sec) to Google Analytics on the virtual pageview event.

When the virtual pageview event occurs (which triggers your virtual pageviews), retrieve the difference between the current time (Date.now()) and the time which the timer was started (time1).

Using Google Tag Manager, a custom javascript variable can be created as below:

function(){
  return (Date.now() - time1)/1000
}

This value then needs to be sent with the pageview, against the custom metric index set up in step1.

ga('send', 'pageview', {
  'metricX': pageLoadSpeed
});

Using the custom metric along with calculated metrics (e.g. {{virtualPageTimings}}/{{pageViews}}, you will be able to calculate your average virtual page timings.

Bonus:

To make the measurement more accurate, set up a secondary custom metric to count the number of virtual pageviews. This will make sure that pageviews which users are directly navigating to are not taken into consideration.

To do this, create a custom metric with the scope hit and the formatting integer.

Then with every virtual pageview, send the value 1 against the custom metric index. E.g:

ga('send', 'pageview', {
  'metricX': pageLoadSpeed,
  'metricX': 1
});

This allows for the calculated metric:

{{virtualPageTimings}}/{{virtualPageViews}}
like image 166
sdhaus Avatar answered Oct 12 '22 03:10

sdhaus