Track user timing with gtag.js

Reducing page load time can improve the overall user experience of a site. This page describes how to send user timing information to Google Analytics.

Implementation

Use the event command to send a timing_complete event:

gtag('event', 'timing_complete', {<timing_parameters>});

where <timing_parameters> is one or more parameter-value pairs. Separate each pair by a comma. For example, this command sends a user timing event to Google Analytics indicating that it took 3549 milliseconds for the current web page to load all external JavaScript dependencies.

gtag('event', 'timing_complete', {
  'name' : 'load',
  'value' : 3549,
  'event_category' : 'JS Dependencies'
});

User timings parameters

This table summarizes the user timings parameters:

Parameter name Data type Required Description
name string Yes A string to identify the variable being recorded (e.g. 'load').
value integer Yes The number of milliseconds in elapsed time to report to Google Analytics (e.g. 20).
event_category string No A string for categorizing all user timing variables into logical groups (e.g. 'JS Dependencies').
event_label string No A string that can be used to add flexibility in visualizing user timings in the reports (e.g. 'Google CDN').

Measuring time

The timing_complete event requires a value parameter that specifies the elapsed time in milliseconds. You need to write code that captures this value.

The easiest way to do this is to create a timestamp at the beginning of a period of time and create another timestamp at the end of the period. Then, calculate the time elapsed between timestamps.

Most modern browsers support the Navigation Timing API, which includes methods on the window.performance object for measuring the performance of web pages through high-resolution time data.

The following example uses the performance.now() method, which returns the amount of time that has elapsed since the page first started loading:

// Feature detects Navigation Timing API support.
if (window.performance) {
  // Gets the number of milliseconds since page load
  // (and rounds the result since the value must be an integer).
  var timeSincePageLoad = Math.round(performance.now());

  // Sends the timing event to Google Analytics.
  gtag('event', 'timing_complete', {
    'name': 'load',
    'value': timeSincePageLoad,
    'event_category': 'JS Dependencies'
  });
}

Sampling considerations

Google Analytics will sample timing events to ensure an equitable distribution of system resources for this feature.

The rate at which timing events are sampled is determined by the total number of pageviews received during the previous day for the property. The following table outlines how the timing sampling rate is determined:

Total pageview count (previous day) Maximum number of timing events that will be processed
0 - 1,000 100
1,000 - 100,000 10% of total pageview count
100,000 - 1,000,000 10,000
1,000,000+ 1% of total pageview count