Custom front-end performance metrics with the User Timing API

1 Apr 2019

Browsers collect a bunch of general-purpose performance metrics when loading a page. For example, you can check when the Load event fired or use the PerformancePaintTiming API to see when content first appeared on the screen.

The problem with these metrics is that they aren't tailored to the needs of your users. If you build a chat app the most important thing might be that messages are rendered quickly, even if the user can't send messages yet. For a game you might want to wait until all graphical assets are loaded, but not worry too much about the soundtrack being ready.

The solution to this is the User Timing API which allows you to define custom performance metrics that track what's most important to your users. For example, Twitter used "Time to first tweet" as an important metric.

Storing a timestamp with performance.mark

The mark function is the core of the User Timing API. It captures a timestamp at the current time and assigns a name to it:

performance.mark("Start Rendering")

You can then access the timings with performance.getEntriesByType("mark"):

Example of the created user timing mark in the console

Measuring elapsed time with performance.measure

If you want to track the duration of a specific step you can use performance.measure. It takes three arguments:

  • The name of the timespan being measured
  • The name of the performance.mark entry at the start
  • The name of the performance.mark entry at the end

Here's an example:

performance.mark("Start rendering")
for (var i=0; i< 1000;i++) {
   document.body.innerHTML += Math.random().toString().slice(1) + " "
performance.mark("Finish rendering")
performance.measure("Rendering", "Start rendering", "Finish rendering")

We can read the measure duration from performance.getEntriesByType("measure"), and it also shows up in the DevTools performance tab:

Screenshot showing user timings in the the Performance tab of Chrome DevTools

In development mode React also uses this API to track component timings automatically:

Example of React component timings in the DevTools Performance tab

Monitoring user timings in DebugBear

If you monitor your site with DebugBear your metrics will show up in the Performance tab automatically:

Chart showing how user timings are monitored continuously

DebugBear is a website monitoring tool built for front-end teams. Track performance metrics and Lighthouse scores in CI and production. Learn more.

Get new articles on web performance by email.

DebugBear logo
Track and analyze site speed with DebugBear.
➔ Learn more