--- url: "https://web.dev/articles/custom-metrics" titulek: "Custom metrics | Articles | web.dev" h1: "Custom metrics Stay organized with collections Save and categorize content based on your preferences." popis: "Custom metrics let you measure and optimize aspects of your site's experience that are unique to your site." jazyk: "en" kanonicka: "https://web.dev/articles/custom-metrics" drobecky: ["Articles", "Custom metrics"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-13 22:27:04" znaku: 19127 slov: 2476 kodovani: "iso-8859-2" sha256: "f64d9edd1c0de35f2b32b8263a13640e34c33c05f19dfef6cae218c2b544e71d" --- Custom metrics Stay organized with collections Save and categorize content based on your preferences. Philip Walton There's a lot of value in having [user-centric metrics](/articles/user-centric-performance-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](https://addyosmani.com/blog/rehydration/). 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 52 79 57 11 [Source](https://developer.mozilla.org/docs/Web/API/PerformanceObserver) 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](https://w3c.github.io/requestidlecallback/#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()`](https://developer.mozilla.org/docs/Web/API/PerformanceObserver/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`](https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute) 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](https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer) the first time that your `PerformanceObserver` callback is called, up to the [maximum buffer size for that type](https://w3c.github.io/timing-entrytypes-registry/#registry). `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`](https://w3c.github.io/performance-timeline/) object: [`getEntries()`](https://developer.mozilla.org/docs/Web/API/Performance/getEntries) [`getEntriesByName()`](https://developer.mozilla.org/docs/Web/API/Performance/getEntriesByName) [`getEntriesByType()`](https://developer.mozilla.org/docs/Web/API/Performance/getEntriesByType) 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 28 12 38 11 [Source](https://developer.mozilla.org/docs/Web/API/PerformanceMark) The [User Timing API](https://w3c.github.io/user-timing/) 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](https://developer.chrome.com/blog/new-in-devtools-67/#tabs), 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 58 79 x x [Source](https://developer.mozilla.org/docs/Web/API/PerformanceLongTaskTiming) The [Long Tasks API](https://w3c.github.io/longtasks/) 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)](/articles/tti) and [Total Blocking Time (TBT)](https://developer.chrome.com/docs/lighthouse/performance/lighthouse-total-blocking-time)). To determine when long tasks happen, you can use [PerformanceObserver](https://developer.mozilla.org/docs/Web/API/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 123 123 x x [Source](https://developer.mozilla.org/docs/Web/API/PerformanceLongAnimationFrameTiming) The [Long Animation Frames API](https://w3c.github.io/long-animation-frames/) 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](https://developer.chrome.com/docs/web-platform/long-animation-frames#long-tasks-shortcomings), including better attribution and the a wider scope of potentially problematic delays. To determine when long frames happen, you can use [PerformanceObserver](https://developer.mozilla.org/docs/Web/API/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 77 79 x x [Source](https://developer.mozilla.org/docs/Web/API/PerformanceElementTiming) The [Largest Contentful Paint (LCP)](/articles/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](https://wicg.github.io/element-timing/). 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. `

This is text I care about.

` Event Timing API Browser Support 76 79 89 26.2 [Source](https://developer.mozilla.org/docs/Web/API/PerformanceEventTiming) The [Interaction to Next Paint (INP)](/articles/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](https://wicg.github.io/event-timing/). This API exposes a number of timestamps that occur during the event lifecycle, including: [**`startTime`**](https://w3c.github.io/performance-timeline/#dom-performanceentry-starttime): the time when the browser receives the event. [**`processingStart`**](https://wicg.github.io/event-timing/#dom-performanceeventtiming-processingstart): the time when the browser is able to begin processing event handlers for the event. [**`processingEnd`**](https://wicg.github.io/event-timing/#dom-performanceeventtiming-processingend): time when the browser finishes executing all synchronous code initiated from event handlers for this event. [**`duration`**](https://wicg.github.io/event-timing/#dom-performanceeventtiming-processingstart): 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 29 12 35 11 [Source](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming) The [Resource Timing API](https://w3c.github.io/resource-timing/) 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](https://w3c.github.io/resource-timing/#processing-model)). Other data you can access includes: [**`initiatorType`**](https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-initiatortype): how the resource was fetched: such as from a `