Custom metrics

There's a lot of value in having user-centric metrics that you can measure, universally, on any given website. These metrics let you:

  • Understand how real users experience the web as a whole.
  • Compare your site to a competitor's.
  • Track useful and actionable data in your analytics tools without needing to write custom code.

Universal metrics offer a good baseline, but in many cases you need to measure more than just these metrics in order to capture the full experience for your particular site.

Custom metrics let you measure aspects of your site's experience that may only apply to your site, such as:

  • How long it takes for a single page app (SPA) to transition from one "page" to another.
  • How long it takes for a page to display data fetched from a database for logged-in users.
  • How long it takes for a server-side-rendered (SSR) app to hydrate.
  • The cache hit rate for resources loaded by returning visitors.
  • The event latency of click or keyboard events in a game.

APIs to measure custom metrics

Historically web developers haven't had many low-level APIs to measure performance, and as a result they've had to resort to hacks in order to measure whether a site was performing well.

For example, it's possible to determine whether the main thread is blocked due to long-running JavaScript tasks by running a requestAnimationFrame loop and calculating the delta between each frame. If the delta is significantly longer than the display's framerate, you can report that as a long task. Such hacks are not recommended, though, because they actually affect performance themselves (by draining battery, for example).

The first rule of effective performance measurement is to make sure your performance measurement techniques aren't causing performance issues themselves. So for any custom metrics you measure on your site, it's best to use one of the following APIs if possible.

Performance Observer API

Browser Support

  • Chrome: 52.
  • Edge: 79.
  • Firefox: 57.
  • Safari: 11.

Source

The Performance Observer API is the mechanism that collects and displays data from all other performance APIs discussed on this page. Understanding it is critical to getting good data.

You can use PerformanceObserver to passively subscribe to performance-related events. This lets API callbacks fire during idle periods, which means they usually won't interfere with page performance.

To create a PerformanceObserver, pass it a callback to be run whenever new performance entries are dispatched. Then you tell the observer what types of entries to listen for using the observe() method:

const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// Log the entry and all associated details.
    console
.log(entry.toJSON());
 
}
});

po
.observe({type: 'some-entry-type'});

The following sections list all the various entry types available for observing, but in newer browsers, you can inspect what entry types are available through the static PerformanceObserver.supportedEntryTypes property.

Observe entries that already happened

By default, PerformanceObserver objects can only observe entries as they occur. This can cause problems if you want to lazy-load your performance analytics code so it doesn't block higher-priority resources.

To get historical entries (after they've occurred), set the buffered flag to true when you call observe(). The browser will include historical entries from its performance entry buffer the first time that your PerformanceObserver callback is called, up to the maximum buffer size for that type.

po.observe({
  type
: 'some-entry-type',
  buffered
: true,
});

Legacy performance APIs to avoid

Prior to the Performance Observer API, developers could access performance entries using the following three methods defined on the performance object:

While these APIs are still supported, their usage is not recommended because they don't let you listen for when new entries are emitted. In addition, many new APIs (such as largest-contentful-paint) are not exposed through the performance object, they're only exposed through PerformanceObserver.

Unless you specifically need compatibility with Internet Explorer, it's best to avoid these methods in your code and use PerformanceObserver going forward.

User Timing API

Browser Support

  • Chrome: 28.
  • Edge: 12.
  • Firefox: 38.
  • Safari: 11.

Source

The User Timing API is a general-purpose measurement API for time-based metrics. It lets you arbitrarily mark points in time and then measure the duration between those marks later.

// Record the time immediately before running a task.
performance
.mark('myTask:start');
await doMyTask
();

// Record the time immediately after running a task.
performance
.mark('myTask:end');

// Measure the delta between the start and end of the task
performance
.measure('myTask', 'myTask:start', 'myTask:end');

While APIs like Date.now() or performance.now() give you similar abilities, the benefit of using the User Timing API is it integrates well with performance tooling. For example, Chrome DevTools visualizes User Timing measurements in the Performance panel, and many analytics providers will also automatically track any measurements you make and send the duration data to their analytics backend.

To report User Timing measurements, you can use PerformanceObserver and register to observe entries of type measure:

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// Log the entry and all associated details.
    console
.log(entry.toJSON());
 
}
});

// Start listening for `measure` entries to be dispatched.
po
.observe({type: 'measure', buffered: true});

Long Tasks API

Browser Support

  • Chrome: 58.
  • Edge: 79.
  • Firefox: not supported.
  • Safari: not supported.

Source

The Long Tasks API is useful for knowing when the browser's main thread is blocked for long enough to affect frame rate or input latency. The API will report any tasks that execute for longer than 50 milliseconds.

Anytime you need to run expensive code, or load and execute large scripts, it's useful to track whether that code blocks the main thread. In fact, many higher-level metrics are built on top of the Long Tasks API themselves (such as Time to Interactive (TTI) and Total Blocking Time (TBT)).

To determine when long tasks happen, you can use PerformanceObserver and register to observe entries of type longtask:

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// Log the entry and all associated details.
    console
.log(entry.toJSON());
 
}
});

// Start listening for `longtask` entries to be dispatched.
po
.observe({type: 'longtask', buffered: true});

Long Animation Frames API

Browser Support

  • Chrome: 123.
  • Edge: 123.
  • Firefox: not supported.
  • Safari: not supported.

Source

The Long Animation Frames API is a new iteration of the Long Tasks API that looks at long frames—rather than long tasks—of over 50 milliseconds. This addresses some shortcomings of the Long Tasks API, including better attribution and the a wider scope of potentially problematic delays.

To determine when long frames happen, you can use PerformanceObserver and register to observe entries of type long-animation-frame:

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// Log the entry and all associated details.
    console
.log(entry.toJSON());
 
}
});

// Start listening for `long-animation-frame` entries to be dispatched.
po
.observe({type: 'long-animation-frame', buffered: true});

Element Timing API

Browser Support

  • Chrome: 77.
  • Edge: 79.
  • Firefox: not supported.
  • Safari: not supported.

Source

The Largest Contentful Paint (LCP) metric is useful for knowing when the largest image or text block was painted to the screen, but in some cases you want to measure the render time of a different element.

For these cases, use the Element Timing API. The LCP API is actually built on top of the Element Timing API and adds automatic reporting of the largest contentful element, but you can also report on other elements by explicitly adding the elementtiming attribute to them, and registering a PerformanceObserver to observe the element entry type.

<img elementtiming="hero-image" />
<p elementtiming="important-paragraph">This is text I care about.</p>
<!-- ... -->

<script>
 
const po = new PerformanceObserver((entryList) => {
   
for (const entry of entryList.getEntries()) {
     
// Log the entry and all associated details.
      console
.log(entry.toJSON());
   
}
 
});

 
// Start listening for `element` entries to be dispatched.
  po
.observe({type: 'element', buffered: true});
</script>

Event Timing API

Browser Support

  • Chrome: 76.
  • Edge: 79.
  • Firefox: 89.
  • Safari: not supported.

Source

The Interaction to Next Paint (INP) metric assesses overall page responsiveness by observing all click, tap, and keyboard interactions throughout the life of a page. A page's INP is most often the interaction that took the longest to complete, from the time the user initiated the interaction, to the time the browser paints the next frame showing the visual result of the user's input.

The INP metric is made possible by the Event Timing API. This API exposes a number of timestamps that occur during the event lifecycle, including:

  • startTime: the time when the browser receives the event.
  • processingStart: the time when the browser is able to begin processing event handlers for the event.
  • processingEnd: time when the browser finishes executing all synchronous code initiated from event handlers for this event.
  • duration: the time (rounded to 8 milliseconds for security reasons) between when the browser receives the event until it's able to paint the next frame after finishing executing all synchronous code initiated from the event handlers.

The following example shows how to use these these values to create custom measurements:

const po = new PerformanceObserver((entryList) => {
 
// Get the last interaction observed:
 
const entries = Array.from(entryList.getEntries()).forEach((entry) => {
   
// Get various bits of interaction data:
   
const inputDelay = entry.processingStart - entry.startTime;
   
const processingTime = entry.processingEnd - entry.processingStart;
   
const presentationDelay = entry.startTime + entry.duration - entry.processingEnd;
   
const duration = entry.duration;
   
const eventType = entry.name;
   
const target = entry.target || "(not set)"

    console
.log("----- INTERACTION -----");
    console
.log(`Input delay (ms): ${inputDelay}`);
    console
.log(`Event handler processing time (ms): ${processingTime}`);
    console
.log(`Presentation delay (ms): ${presentationDelay}`);
    console
.log(`Total event duration (ms): ${duration}`);
    console
.log(`Event type: ${eventType}`);
    console
.log(target);
 
});
});

// A durationThreshold of 16ms is necessary to include more
// interactions, since the default is 104ms. The minimum
// durationThreshold is 16ms.
po
.observe({type: 'event', buffered: true, durationThreshold: 16});

Resource Timing API

Browser Support

  • Chrome: 29.
  • Edge: 12.
  • Firefox: 35.
  • Safari: 11.

Source

The Resource Timing API gives developers detailed insight into how resources for a particular page were loaded. Despite the name of the API, the information it provides is not just limited to timing data (though there's plenty of that). Other data you can access includes:

  • initiatorType: how the resource was fetched: such as from a <script> or <link> tag, or from a fetch() call.
  • nextHopProtocol: the protocol used to fetch the resource, such as h2 or quic.
  • encodedBodySize/decodedBodySize]: the size of the resource in its encoded or decoded form (respectively)
  • transferSize: the size of the resource that was actually transferred over the network. When resources are fulfilled by the cache, this value can be much smaller than the encodedBodySize, and in some cases it can be zero (if no cache revalidation is required).

You can use the transferSize property of resource timing entries to measure a cache hit rate metric or a total cached resource size metric, which can be useful in understanding how your resource caching strategy affects performance for repeat visitors.

The following example logs all resources requested by the page and indicates whether or not each resource was fulfilled by the cache.

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// If transferSize is 0, the resource was fulfilled using the cache.
    console
.log(entry.name, entry.transferSize === 0);
 
}
});

// Start listening for `resource` entries to be dispatched.
po
.observe({type: 'resource', buffered: true});

Browser Support

  • Chrome: 57.
  • Edge: 12.
  • Firefox: 58.
  • Safari: 15.

Source

The Navigation Timing API is similar to the Resource Timing API, but it reports only navigation requests. The navigation entry type is also similar to the resource entry type, but it contains some additional information specific to only navigation requests (such as when the DOMContentLoaded and load events fire).

One metric many developers track to understand server response time (Time to First Byte (TTFB)) is available using the Navigation Timing API—specifically it's entry's responseStart timestamp.

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// If transferSize is 0, the resource was fulfilled using the cache.
    console
.log('Time to first byte', entry.responseStart);
 
}
});

// Start listening for `navigation` entries to be dispatched.
po
.observe({type: 'navigation', buffered: true});

Another metric developers who use service worker may care about is the service worker startup time for navigation requests. This is the amount of time it takes the browser to start the service worker thread before it can start intercepting fetch events.

The service worker startup time for a particular navigation request can be determined from the delta between entry.responseStart and entry.workerStart.

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
    console
.log('Service Worker startup time:',
        entry
.responseStart - entry.workerStart);
 
}
});

// Start listening for `navigation` entries to be dispatched.
po
.observe({type: 'navigation', buffered: true});

Server Timing API

Browser Support

  • Chrome: 65.
  • Edge: 79.
  • Firefox: 61.
  • Safari: 16.4.

Source

The Server Timing API let you pass request-specific timing data from your server to the browser through response headers. For example, you can indicate how long it took to lookup data in a database for a particular request—which can be useful in debugging performance issues caused by slowness on the server.

For developers who use third-party analytics providers, the Server Timing API is the only way to correlate server performance data with other business metrics that these analytics tools may be measuring.

To specify server timing data in your responses, you can use the Server-Timing response header. Here's an example.

HTTP/1.1 200 OK

Server-Timing: miss, db;dur=53, app;dur=47.2

Then, from your pages, you can read this data on both resource or navigation entries from the Resource Timing and Navigation Timing APIs.

// Create the performance observer.
const po = new PerformanceObserver((list) => {
 
for (const entry of list.getEntries()) {
   
// Logs all server timing data for this response
    console
.log('Server Timing', entry.serverTiming);
 
}
});

// Start listening for `navigation` entries to be dispatched.
po
.observe({type: 'navigation', buffered: true});