UNPKG

49.4 kBMarkdownView Raw
1# `web-vitals`
2
3- [Overview](#overview)
4- [Install and load the library](#installation)
5 - [From npm](#import-web-vitals-from-npm)
6 - [From a CDN](#load-web-vitals-from-a-cdn)
7- [Usage](#usage)
8 - [Basic usage](#basic-usage)
9 - [Report the value on every change](#report-the-value-on-every-change)
10 - [Report only the delta of changes](#report-only-the-delta-of-changes)
11 - [Send the results to an analytics endpoint](#send-the-results-to-an-analytics-endpoint)
12 - [Send the results to Google Analytics](#send-the-results-to-google-analytics)
13 - [Send the results to Google Tag Manager](#send-the-results-to-google-tag-manager)
14 - [Send attribution data](#send-attribution-data)
15 - [Batch multiple reports together](#batch-multiple-reports-together)
16- [Build options](#build-options)
17 - [Which build is right for you?](#which-build-is-right-for-you)
18- [API](#api)
19 - [Types](#types)
20 - [Functions](#functions)
21 - [Rating Thresholds](#rating-thresholds)
22 - [Attribution](#attribution)
23- [Browser Support](#browser-support)
24- [Limitations](#limitations)
25- [Development](#development)
26- [Integrations](#integrations)
27- [License](#license)
28
29## Overview
30
31The `web-vitals` library is a tiny (~2K, brotli'd), modular library for measuring all the [Web Vitals](https://web.dev/articles/vitals) metrics on real users, in a way that accurately matches how they're measured by Chrome and reported to other Google tools (e.g. [Chrome User Experience Report](https://developers.google.com/web/tools/chrome-user-experience-report), [Page Speed Insights](https://developers.google.com/speed/pagespeed/insights/), [Search Console's Speed Report](https://webmasters.googleblog.com/2019/11/search-console-speed-report.html)).
32
33The library supports all of the [Core Web Vitals](https://web.dev/articles/vitals#core_web_vitals) as well as a number of other metrics that are useful in diagnosing [real-user](https://web.dev/articles/user-centric-performance-metrics) performance issues.
34
35### Core Web Vitals
36
37- [Cumulative Layout Shift (CLS)](https://web.dev/articles/cls)
38- [Interaction to Next Paint (INP)](https://web.dev/articles/inp)
39- [Largest Contentful Paint (LCP)](https://web.dev/articles/lcp)
40
41### Other metrics
42
43- [First Contentful Paint (FCP)](https://web.dev/articles/fcp)
44- [Time to First Byte (TTFB)](https://web.dev/articles/ttfb)
45- [First Input Delay (FID)](https://web.dev/articles/fid) _Deprecated and will be removed in next major release_
46
47<a name="installation"><a>
48<a name="load-the-library"><a>
49
50## Install and load the library
51
52<a name="import-web-vitals-from-npm"><a>
53
54The `web-vitals` library uses the `buffered` flag for [PerformanceObserver](https://developer.mozilla.org/docs/Web/API/PerformanceObserver/observe), allowing it to access performance entries that occurred before the library was loaded.
55
56This means you do not need to load this library early in order to get accurate performance data. In general, this library should be deferred until after other user-impacting code has loaded.
57
58### From npm
59
60You can install this library from npm by running:
61
62```sh
63npm install web-vitals
64```
65
66_**Note:** If you're not using npm, you can still load `web-vitals` via `<script>` tags from a CDN like [unpkg.com](https://unpkg.com). See the [load `web-vitals` from a CDN](#load-web-vitals-from-a-cdn) usage example below for details._
67
68There are a few different builds of the `web-vitals` library, and how you load the library depends on which build you want to use.
69
70For details on the difference between the builds, see <a href="#which-build-is-right-for-you">which build is right for you</a>.
71
72**1. The "standard" build**
73
74To load the "standard" build, import modules from the `web-vitals` package in your application code (as you would with any npm package and node-based build tool):
75
76```js
77import {onLCP, onINP, onCLS} from 'web-vitals';
78
79onCLS(console.log);
80onINP(console.log);
81onLCP(console.log);
82```
83
84_**Note:** in version 2, these functions were named `getXXX()` rather than `onXXX()`. They've [been renamed](https://github.com/GoogleChrome/web-vitals/pull/222) in version 3 to reduce confusion (see [#217](https://github.com/GoogleChrome/web-vitals/pull/217) for details) and will continue to be available using the `getXXX()` until at least version 4. Users are encouraged to switch to the new names, though, for future compatibility._
85
86<a name="attribution-build"><a>
87
88**2. The "attribution" build**
89
90Measuring the Web Vitals scores for your real users is a great first step toward optimizing the user experience. But if your scores aren't _good_, the next step is to understand why they're not good and work to improve them.
91
92The "attribution" build helps you do that by including additional diagnostic information with each metric to help you identify the root cause of poor performance as well as prioritize the most important things to fix.
93
94The "attribution" build is slightly larger than the "standard" build (by about 600 bytes, brotli'd), so while the code size is still small, it's only recommended if you're actually using these features.
95
96To load the "attribution" build, change any `import` statements that reference `web-vitals` to `web-vitals/attribution`:
97
98```diff
99- import {onLCP, onINP, onCLS} from 'web-vitals';
100+ import {onLCP, onINP, onCLS} from 'web-vitals/attribution';
101```
102
103Usage for each of the imported function is identical to the standard build, but when importing from the attribution build, the [metric](#metric) objects will contain an additional [`attribution`](#attribution) property.
104
105See [Send attribution data](#send-attribution-data) for usage examples, and the [`attribution` reference](#attribution) for details on what values are added for each metric.
106
107<a name="load-web-vitals-from-a-cdn"><a>
108
109### From a CDN
110
111The recommended way to use the `web-vitals` package is to install it from npm and integrate it into your build process. However, if you're not using npm, it's still possible to use `web-vitals` by requesting it from a CDN that serves npm package files.
112
113The following examples show how to load `web-vitals` from [unpkg.com](https://unpkg.com/browse/web-vitals/). It is also possible to load this from [jsDelivr](https://www.jsdelivr.com/package/npm/web-vitals), and [cdnjs](https://cdnjs.com/libraries/web-vitals).
114
115_**Important!** The [unpkg.com](https://unpkg.com), [jsDelivr](https://www.jsdelivr.com/), and [cdnjs](https://cdnjs.com) CDNs are shown here for example purposes only. `unpkg.com`, `jsDelivr`, and `cdnjs` are not affiliated with Google, and there are no guarantees that loading the library from those CDNs will continue to work in the future. Self-hosting the built files rather than loading from the CDN is better for security, reliability, and performance reasons._
116
117**Load the "standard" build** _(using a module script)_
118
119```html
120<!-- Append the `?module` param to load the module version of `web-vitals` -->
121<script type="module">
122 import {onCLS, onINP, onLCP} from 'https://unpkg.com/web-vitals@4?module';
123
124 onCLS(console.log);
125 onINP(console.log);
126 onLCP(console.log);
127</script>
128```
129
130**Load the "standard" build** _(using a classic script)_
131
132```html
133<script>
134 (function () {
135 var script = document.createElement('script');
136 script.src = 'https://unpkg.com/web-vitals@4/dist/web-vitals.iife.js';
137 script.onload = function () {
138 // When loading `web-vitals` using a classic script, all the public
139 // methods can be found on the `webVitals` global namespace.
140 webVitals.onCLS(console.log);
141 webVitals.onINP(console.log);
142 webVitals.onLCP(console.log);
143 };
144 document.head.appendChild(script);
145 })();
146</script>
147```
148
149**Load the "attribution" build** _(using a module script)_
150
151```html
152<!-- Append the `?module` param to load the module version of `web-vitals` -->
153<script type="module">
154 import {
155 onCLS,
156 onINP,
157 onLCP,
158 } from 'https://unpkg.com/web-vitals@4/dist/web-vitals.attribution.js?module';
159
160 onCLS(console.log);
161 onINP(console.log);
162 onLCP(console.log);
163</script>
164```
165
166**Load the "attribution" build** _(using a classic script)_
167
168```html
169<script>
170 (function () {
171 var script = document.createElement('script');
172 script.src =
173 'https://unpkg.com/web-vitals@4/dist/web-vitals.attribution.iife.js';
174 script.onload = function () {
175 // When loading `web-vitals` using a classic script, all the public
176 // methods can be found on the `webVitals` global namespace.
177 webVitals.onCLS(console.log);
178 webVitals.onINP(console.log);
179 webVitals.onLCP(console.log);
180 };
181 document.head.appendChild(script);
182 })();
183</script>
184```
185
186## Usage
187
188### Basic usage
189
190Each of the Web Vitals metrics is exposed as a single function that takes a `callback` function that will be called any time the metric value is available and ready to be reported.
191
192The following example measures each of the Core Web Vitals metrics and logs the result to the console once its value is ready to report.
193
194_(The examples below import the "standard" build, but they will work with the "attribution" build as well.)_
195
196```js
197import {onCLS, onINP, onLCP} from 'web-vitals';
198
199onCLS(console.log);
200onINP(console.log);
201onLCP(console.log);
202```
203
204Note that some of these metrics will not report until the user has interacted with the page, switched tabs, or the page starts to unload. If you don't see the values logged to the console immediately, try reloading the page (with [preserve log](https://developer.chrome.com/docs/devtools/console/reference/#persist) enabled) or switching tabs and then switching back.
205
206Also, in some cases a metric callback may never be called:
207
208- FID and INP are not reported if the user never interacts with the page.
209- CLS, FCP, FID, and LCP are not reported if the page was loaded in the background.
210
211In other cases, a metric callback may be called more than once:
212
213- CLS and INP should be reported any time the [page's `visibilityState` changes to hidden](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden).
214- All metrics are reported again (with the above exceptions) after a page is restored from the [back/forward cache](https://web.dev/articles/bfcache).
215
216_**Warning:** do not call any of the Web Vitals functions (e.g. `onCLS()`, `onINP()`, `onLCP()`) more than once per page load. Each of these functions creates a `PerformanceObserver` instance and registers event listeners for the lifetime of the page. While the overhead of calling these functions once is negligible, calling them repeatedly on the same page may eventually result in a memory leak._
217
218### Report the value on every change
219
220In most cases, you only want the `callback` function to be called when the metric is ready to be reported. However, it is possible to report every change (e.g. each larger layout shift as it happens) by setting `reportAllChanges` to `true` in the optional, [configuration object](#reportopts) (second parameter).
221
222_**Important:** `reportAllChanges` only reports when the **metric changes**, not for each **input to the metric**. For example, a new layout shift that does not increase the CLS metric will not be reported even with `reportAllChanges` set to `true` because the CLS metric has not changed. Similarly, for INP, each interaction is not reported even with `reportAllChanges` set to `true`—just when an interaction causes an increase to INP._
223
224This can be useful when debugging, but in general using `reportAllChanges` is not needed (or recommended) for measuring these metrics in production.
225
226```js
227import {onCLS} from 'web-vitals';
228
229// Logs CLS as the value changes.
230onCLS(console.log, {reportAllChanges: true});
231```
232
233### Report only the delta of changes
234
235Some analytics providers allow you to update the value of a metric, even after you've already sent it to their servers (overwriting the previously-sent value with the same `id`).
236
237Other analytics providers, however, do not allow this, so instead of reporting the new value, you need to report only the delta (the difference between the current value and the last-reported value). You can then compute the total value by summing all metric deltas sent with the same ID.
238
239The following example shows how to use the `id` and `delta` properties:
240
241```js
242import {onCLS, onINP, onLCP} from 'web-vitals';
243
244function logDelta({name, id, delta}) {
245 console.log(`${name} matching ID ${id} changed by ${delta}`);
246}
247
248onCLS(logDelta);
249onINP(logDelta);
250onLCP(logDelta);
251```
252
253_**Note:** the first time the `callback` function is called, its `value` and `delta` properties will be the same._
254
255In addition to using the `id` field to group multiple deltas for the same metric, it can also be used to differentiate different metrics reported on the same page. For example, after a back/forward cache restore, a new metric object is created with a new `id` (since back/forward cache restores are considered separate page visits).
256
257### Send the results to an analytics endpoint
258
259The following example measures each of the Core Web Vitals metrics and reports them to a hypothetical `/analytics` endpoint, as soon as each is ready to be sent.
260
261The `sendToAnalytics()` function uses the [`navigator.sendBeacon()`](https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon) method (if available), but falls back to the [`fetch()`](https://developer.mozilla.org/docs/Web/API/Fetch_API) API when not.
262
263```js
264import {onCLS, onINP, onLCP} from 'web-vitals';
265
266function sendToAnalytics(metric) {
267 // Replace with whatever serialization method you prefer.
268 // Note: JSON.stringify will likely include more data than you need.
269 const body = JSON.stringify(metric);
270
271 // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
272 (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
273 fetch('/analytics', {body, method: 'POST', keepalive: true});
274}
275
276onCLS(sendToAnalytics);
277onINP(sendToAnalytics);
278onLCP(sendToAnalytics);
279```
280
281### Send the results to Google Analytics
282
283Google Analytics does not support reporting metric distributions in any of its built-in reports; however, if you set a unique event parameter value (in this case, the metric_id, as shown in the example below) on every metric instance that you send to Google Analytics, you can create a report yourself by first getting the data via the [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) or via [BigQuery export](https://support.google.com/analytics/answer/9358801) and then visualizing it any charting library you choose.
284
285[Google Analytics 4](https://support.google.com/analytics/answer/10089681) introduces a new Event model allowing custom parameters instead of a fixed category, action, and label. It also supports non-integer values, making it easier to measure Web Vitals metrics compared to previous versions.
286
287```js
288import {onCLS, onINP, onLCP} from 'web-vitals';
289
290function sendToGoogleAnalytics({name, delta, value, id}) {
291 // Assumes the global `gtag()` function exists, see:
292 // https://developers.google.com/analytics/devguides/collection/ga4
293 gtag('event', name, {
294 // Built-in params:
295 value: delta, // Use `delta` so the value can be summed.
296 // Custom params:
297 metric_id: id, // Needed to aggregate events.
298 metric_value: value, // Optional.
299 metric_delta: delta, // Optional.
300
301 // OPTIONAL: any additional params or debug info here.
302 // See: https://web.dev/articles/debug-performance-in-the-field
303 // metric_rating: 'good' | 'needs-improvement' | 'poor',
304 // debug_info: '...',
305 // ...
306 });
307}
308
309onCLS(sendToGoogleAnalytics);
310onINP(sendToGoogleAnalytics);
311onLCP(sendToGoogleAnalytics);
312```
313
314For details on how to query this data in [BigQuery](https://cloud.google.com/bigquery), or visualise it in [Looker Studio](https://lookerstudio.google.com/), see [Measure and debug performance with Google Analytics 4 and BigQuery](https://web.dev/articles/vitals-ga4).
315
316### Send the results to Google Tag Manager
317
318While `web-vitals` can be called directly from Google Tag Manager, using a pre-defined custom template makes this considerably easier. Some recommended templates include:
319
320- [Core Web Vitals](https://tagmanager.google.com/gallery/#/owners/gtm-templates-simo-ahava/templates/core-web-vitals) by [Simo Ahava](https://www.simoahava.com/). See [Track Core Web Vitals in GA4 with Google Tag Manager](https://www.simoahava.com/analytics/track-core-web-vitals-in-ga4-with-google-tag-manager/) for usage and installation instructions.
321- [Web Vitals Template for Google Tag Manager](https://github.com/google-marketing-solutions/web-vitals-gtm-template) by The Google Marketing Solutions team. See the [README](https://github.com/google-marketing-solutions/web-vitals-gtm-template?tab=readme-ov-file#web-vitals-template-for-google-tag-manager) for usage and installation instructions.
322
323### Send attribution data
324
325When using the [attribution build](#attribution-build), you can send additional data to help you debug _why_ the metric values are they way they are.
326
327This example sends an additional `debug_target` param to Google Analytics, corresponding to the element most associated with each metric.
328
329```js
330import {onCLS, onINP, onLCP} from 'web-vitals/attribution';
331
332function sendToGoogleAnalytics({name, delta, value, id, attribution}) {
333 const eventParams = {
334 // Built-in params:
335 value: delta, // Use `delta` so the value can be summed.
336 // Custom params:
337 metric_id: id, // Needed to aggregate events.
338 metric_value: value, // Optional.
339 metric_delta: delta, // Optional.
340 };
341
342 switch (name) {
343 case 'CLS':
344 eventParams.debug_target = attribution.largestShiftTarget;
345 break;
346 case 'INP':
347 eventParams.debug_target = attribution.interactionTarget;
348 break;
349 case 'LCP':
350 eventParams.debug_target = attribution.element;
351 break;
352 }
353
354 // Assumes the global `gtag()` function exists, see:
355 // https://developers.google.com/analytics/devguides/collection/ga4
356 gtag('event', name, eventParams);
357}
358
359onCLS(sendToGoogleAnalytics);
360onINP(sendToGoogleAnalytics);
361onLCP(sendToGoogleAnalytics);
362```
363
364_**Note:** this example relies on custom [event parameters](https://support.google.com/analytics/answer/11396839) in Google Analytics 4._
365
366See [Debug performance in the field](https://web.dev/articles/debug-performance-in-the-field) for more information and examples.
367
368### Batch multiple reports together
369
370Rather than reporting each individual Web Vitals metric separately, you can minimize your network usage by batching multiple metric reports together in a single network request.
371
372However, since not all Web Vitals metrics become available at the same time, and since not all metrics are reported on every page, you cannot simply defer reporting until all metrics are available.
373
374Instead, you should keep a queue of all metrics that were reported and flush the queue whenever the page is backgrounded or unloaded:
375
376```js
377import {onCLS, onINP, onLCP} from 'web-vitals';
378
379const queue = new Set();
380function addToQueue(metric) {
381 queue.add(metric);
382}
383
384function flushQueue() {
385 if (queue.size > 0) {
386 // Replace with whatever serialization method you prefer.
387 // Note: JSON.stringify will likely include more data than you need.
388 const body = JSON.stringify([...queue]);
389
390 // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
391 (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
392 fetch('/analytics', {body, method: 'POST', keepalive: true});
393
394 queue.clear();
395 }
396}
397
398onCLS(addToQueue);
399onINP(addToQueue);
400onLCP(addToQueue);
401
402// Report all available metrics whenever the page is backgrounded or unloaded.
403addEventListener('visibilitychange', () => {
404 if (document.visibilityState === 'hidden') {
405 flushQueue();
406 }
407});
408
409// NOTE: Safari does not reliably fire the `visibilitychange` event when the
410// page is being unloaded. If Safari support is needed, you should also flush
411// the queue in the `pagehide` event.
412addEventListener('pagehide', flushQueue);
413```
414
415_**Note:** see [the Page Lifecycle guide](https://developers.google.com/web/updates/2018/07/page-lifecycle-api#legacy-lifecycle-apis-to-avoid) for an explanation of why `visibilitychange` and `pagehide` are recommended over events like `beforeunload` and `unload`._
416
417<a name="bundle-versions"><a>
418
419## Build options
420
421The `web-vitals` package includes both "standard" and "attribution" builds, as well as different formats of each to allow developers to choose the format that best meets their needs or integrates with their architecture.
422
423The following table lists all the builds distributed with the `web-vitals` package on npm.
424
425<table>
426 <tr>
427 <td width="35%">
428 <strong>Filename</strong> <em>(all within <code>dist/*</code>)</em>
429 </td>
430 <td><strong>Export</strong></td>
431 <td><strong>Description</strong></td>
432 </tr>
433 <tr>
434 <td><code>web-vitals.js</code></td>
435 <td><code>pkg.module</code></td>
436 <td>
437 <p>An ES module bundle of all metric functions, without any attribution features.</p>
438 This is the "standard" build and is the simplest way to consume this library out of the box.
439 </td>
440 </tr>
441 <tr>
442 <td><code>web-vitals.umd.cjs</code></td>
443 <td><code>pkg.main</code></td>
444 <td>
445 A UMD version of the <code>web-vitals.js</code> bundle (exposed on the <code>self.webVitals.*</code> namespace).
446 </td>
447 </tr>
448 <tr>
449 <td><code>web-vitals.iife.js</code></td>
450 <td>--</td>
451 <td>
452 An IIFE version of the <code>web-vitals.js</code> bundle (exposed on the <code>self.webVitals.*</code> namespace).
453 </td>
454 </tr>
455 <tr>
456 <td><code>web-vitals.attribution.js</code></td>
457 <td>--</td>
458 <td>
459 An ES module version of all metric functions that includes <a href="#attribution-build">attribution</a> features.
460 </td>
461 </tr>
462 <tr>
463 <td><code>web-vitals.attribution.umd.cjs</code></td>
464 <td>--</td>
465 <td>
466 A UMD version of the <code>web-vitals.attribution.js</code> build (exposed on the <code>self.webVitals.*</code> namespace).
467 </td>
468 </tr>
469 </tr>
470 <tr>
471 <td><code>web-vitals.attribution.iife.js</code></td>
472 <td>--</td>
473 <td>
474 An IIFE version of the <code>web-vitals.attribution.js</code> build (exposed on the <code>self.webVitals.*</code> namespace).
475 </td>
476 </tr>
477</table>
478
479<a name="which-build-is-right-for-you"><a>
480
481### Which build is right for you?
482
483Most developers will generally want to use "standard" build (via either the ES module or UMD version, depending on your bundler/build system), as it's the easiest to use out of the box and integrate into existing tools.
484
485However, if you'd lke to collect additional debug information to help you diagnose performance bottlenecks based on real-user issues, use the ["attribution" build](#attribution-build).
486
487For guidance on how to collect and use real-user data to debug performance issues, see [Debug performance in the field](https://web.dev/debug-performance-in-the-field/).
488
489## API
490
491### Types:
492
493#### `Metric`
494
495All metrics types inherit from the following base interface:
496
497```ts
498interface Metric {
499 /**
500 * The name of the metric (in acronym form).
501 */
502 name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';
503
504 /**
505 * The current value of the metric.
506 */
507 value: number;
508
509 /**
510 * The rating as to whether the metric value is within the "good",
511 * "needs improvement", or "poor" thresholds of the metric.
512 */
513 rating: 'good' | 'needs-improvement' | 'poor';
514
515 /**
516 * The delta between the current value and the last-reported value.
517 * On the first report, `delta` and `value` will always be the same.
518 */
519 delta: number;
520
521 /**
522 * A unique ID representing this particular metric instance. This ID can
523 * be used by an analytics tool to dedupe multiple values sent for the same
524 * metric instance, or to group multiple deltas together and calculate a
525 * total. It can also be used to differentiate multiple different metric
526 * instances sent from the same page, which can happen if the page is
527 * restored from the back/forward cache (in that case new metrics object
528 * get created).
529 */
530 id: string;
531
532 /**
533 * Any performance entries relevant to the metric value calculation.
534 * The array may also be empty if the metric value was not based on any
535 * entries (e.g. a CLS value of 0 given no layout shifts).
536 */
537 entries: PerformanceEntry[];
538
539 /**
540 * The type of navigation.
541 *
542 * This will be the value returned by the Navigation Timing API (or
543 * `undefined` if the browser doesn't support that API), with the following
544 * exceptions:
545 * - 'back-forward-cache': for pages that are restored from the bfcache.
546 * - 'back_forward' is renamed to 'back-forward' for consistency.
547 * - 'prerender': for pages that were prerendered.
548 * - 'restore': for pages that were discarded by the browser and then
549 * restored by the user.
550 */
551 navigationType:
552 | 'navigate'
553 | 'reload'
554 | 'back-forward'
555 | 'back-forward-cache'
556 | 'prerender'
557 | 'restore';
558}
559```
560
561Metric-specific subclasses:
562
563##### `CLSMetric`
564
565```ts
566interface CLSMetric extends Metric {
567 name: 'CLS';
568 entries: LayoutShift[];
569}
570```
571
572##### `FCPMetric`
573
574```ts
575interface FCPMetric extends Metric {
576 name: 'FCP';
577 entries: PerformancePaintTiming[];
578}
579```
580
581##### `FIDMetric`
582
583_This interface is deprecated and will be removed in next major release_
584
585```ts
586interface FIDMetric extends Metric {
587 name: 'FID';
588 entries: PerformanceEventTiming[];
589}
590```
591
592##### `INPMetric`
593
594```ts
595interface INPMetric extends Metric {
596 name: 'INP';
597 entries: PerformanceEventTiming[];
598}
599```
600
601##### `LCPMetric`
602
603```ts
604interface LCPMetric extends Metric {
605 name: 'LCP';
606 entries: LargestContentfulPaint[];
607}
608```
609
610##### `TTFBMetric`
611
612```ts
613interface TTFBMetric extends Metric {
614 name: 'TTFB';
615 entries: PerformanceNavigationTiming[];
616}
617```
618
619#### `MetricRatingThresholds`
620
621The thresholds of metric's "good", "needs improvement", and "poor" ratings.
622
623- Metric values up to and including [0] are rated "good"
624- Metric values up to and including [1] are rated "needs improvement"
625- Metric values above [1] are "poor"
626
627| Metric value | Rating |
628| --------------- | ------------------- |
629| ≦ [0] | "good" |
630| > [0] and ≦ [1] | "needs improvement" |
631| > [1] | "poor" |
632
633```ts
634type MetricRatingThresholds = [number, number];
635```
636
637_See also [Rating Thresholds](#rating-thresholds)._
638
639#### `ReportOpts`
640
641```ts
642interface ReportOpts {
643 reportAllChanges?: boolean;
644 durationThreshold?: number;
645}
646```
647
648#### `LoadState`
649
650The `LoadState` type is used in several of the metric [attribution objects](#attribution).
651
652```ts
653/**
654 * The loading state of the document. Note: this value is similar to
655 * `document.readyState` but it subdivides the "interactive" state into the
656 * time before and after the DOMContentLoaded event fires.
657 *
658 * State descriptions:
659 * - `loading`: the initial document response has not yet been fully downloaded
660 * and parsed. This is equivalent to the corresponding `readyState` value.
661 * - `dom-interactive`: the document has been fully loaded and parsed, but
662 * scripts may not have yet finished loading and executing.
663 * - `dom-content-loaded`: the document is fully loaded and parsed, and all
664 * scripts (except `async` scripts) have loaded and finished executing.
665 * - `complete`: the document and all of its sub-resources have finished
666 * loading. This is equivalent to the corresponding `readyState` value.
667 */
668type LoadState =
669 | 'loading'
670 | 'dom-interactive'
671 | 'dom-content-loaded'
672 | 'complete';
673```
674
675### Functions:
676
677#### `onCLS()`
678
679```ts
680function onCLS(callback: (metric: CLSMetric) => void, opts?: ReportOpts): void;
681```
682
683Calculates the [CLS](https://web.dev/articles/cls) value for the current page and calls the `callback` function once the value is ready to be reported, along with all `layout-shift` performance entries that were used in the metric value calculation. The reported value is a [double](https://heycam.github.io/webidl/#idl-double) (corresponding to a [layout shift score](https://web.dev/articles/cls#layout_shift_score)).
684
685If the `reportAllChanges` [configuration option](#reportopts) is set to `true`, the `callback` function will be called as soon as the value is initially determined as well as any time the value changes throughout the page lifespan (Note [not necessarily for every layout shift](#report-the-value-on-every-change)).
686
687_**Important:** CLS should be continually monitored for changes throughout the entire lifespan of a page—including if the user returns to the page after it's been hidden/backgrounded. However, since browsers often [will not fire additional callbacks once the user has backgrounded a page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), `callback` is always called when the page's visibility state changes to hidden. As a result, the `callback` function might be called multiple times during the same page load (see [Reporting only the delta of changes](#report-only-the-delta-of-changes) for how to manage this)._
688
689#### `onFCP()`
690
691```ts
692function onFCP(callback: (metric: FCPMetric) => void, opts?: ReportOpts): void;
693```
694
695Calculates the [FCP](https://web.dev/articles/fcp) value for the current page and calls the `callback` function once the value is ready, along with the relevant `paint` performance entry used to determine the value. The reported value is a [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp).
696
697#### `onFID()`
698
699_This function is deprecated and will be removed in next major release_
700
701```ts
702function onFID(callback: (metric: FIDMetric) => void, opts?: ReportOpts): void;
703```
704
705Calculates the [FID](https://web.dev/articles/fid) value for the current page and calls the `callback` function once the value is ready, along with the relevant `first-input` performance entry used to determine the value. The reported value is a [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp).
706
707_**Important:** since FID is only reported after the user interacts with the page, it's possible that it will not be reported for some page loads._
708
709#### `onINP()`
710
711```ts
712function onINP(callback: (metric: INPMetric) => void, opts?: ReportOpts): void;
713```
714
715Calculates the [INP](https://web.dev/articles/inp) value for the current page and calls the `callback` function once the value is ready, along with the `event` performance entries reported for that interaction. The reported value is a [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp).
716
717A custom `durationThreshold` [configuration option](#reportopts) can optionally be passed to control what `event-timing` entries are considered for INP reporting. The default threshold is `40`, which means INP scores of less than 40 are reported as 0. Note that this will not affect your 75th percentile INP value unless that value is also less than 40 (well below the recommended [good](https://web.dev/articles/inp#what_is_a_good_inp_score) threshold).
718
719If the `reportAllChanges` [configuration option](#reportopts) is set to `true`, the `callback` function will be called as soon as the value is initially determined as well as any time the value changes throughout the page lifespan (Note [not necessarily for every interaction](#report-the-value-on-every-change)).
720
721_**Important:** INP should be continually monitored for changes throughout the entire lifespan of a page—including if the user returns to the page after it's been hidden/backgrounded. However, since browsers often [will not fire additional callbacks once the user has backgrounded a page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), `callback` is always called when the page's visibility state changes to hidden. As a result, the `callback` function might be called multiple times during the same page load (see [Reporting only the delta of changes](#report-only-the-delta-of-changes) for how to manage this)._
722
723#### `onLCP()`
724
725```ts
726function onLCP(callback: (metric: LCPMetric) => void, opts?: ReportOpts): void;
727```
728
729Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and calls the `callback` function once the value is ready (along with the relevant `largest-contentful-paint` performance entry used to determine the value). The reported value is a [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp).
730
731If the `reportAllChanges` [configuration option](#reportopts) is set to `true`, the `callback` function will be called any time a new `largest-contentful-paint` performance entry is dispatched, or once the final value of the metric has been determined.
732
733#### `onTTFB()`
734
735```ts
736function onTTFB(
737 callback: (metric: TTFBMetric) => void,
738 opts?: ReportOpts,
739): void;
740```
741
742Calculates the [TTFB](https://web.dev/articles/ttfb) value for the current page and calls the `callback` function once the page has loaded, along with the relevant `navigation` performance entry used to determine the value. The reported value is a [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp).
743
744Note, this function waits until after the page is loaded to call `callback` in order to ensure all properties of the `navigation` entry are populated. This is useful if you want to report on other metrics exposed by the [Navigation Timing API](https://w3c.github.io/navigation-timing/).
745
746For example, the TTFB metric starts from the page's [time origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it includes time spent on DNS lookup, connection negotiation, network latency, and server processing time.
747
748```js
749import {onTTFB} from 'web-vitals';
750
751onTTFB((metric) => {
752 // Calculate the request time by subtracting from TTFB
753 // everything that happened prior to the request starting.
754 const requestTime = metric.value - metric.entries[0].requestStart;
755 console.log('Request time:', requestTime);
756});
757```
758
759_**Note:** browsers that do not support `navigation` entries will fall back to
760using `performance.timing` (with the timestamps converted from epoch time to [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp)). This ensures code referencing these values (like in the example above) will work the same in all browsers._
761
762### Rating Thresholds:
763
764The thresholds of each metric's "good", "needs improvement", and "poor" ratings are available as [`MetricRatingThresholds`](#metricratingthresholds).
765
766Example:
767
768```ts
769import {CLSThresholds, INPThresholds, LCPThresholds} from 'web-vitals';
770
771console.log(CLSThresholds); // [ 0.1, 0.25 ]
772console.log(INPThresholds); // [ 200, 500 ]
773console.log(LCPThresholds); // [ 2500, 4000 ]
774```
775
776_**Note:** It's typically not necessary (or recommended) to manually calculate metric value ratings using these thresholds. Use the [`Metric['rating']`](#metric) instead._
777
778### Attribution:
779
780The following objects contain potentially-helpful debugging information that can be sent along with the metric values for the current page visit in order to help identify issues happening to real-users in the field.
781
782When using the attribution build, these objects are found as an `attribution` property on each metric.
783
784See the [attribution build](#attribution-build) section for details on how to use this feature.
785
786#### `CLSAttribution`
787
788```ts
789interface CLSAttribution {
790 /**
791 * A selector identifying the first element (in document order) that
792 * shifted when the single largest layout shift contributing to the page's
793 * CLS score occurred.
794 */
795 largestShiftTarget?: string;
796 /**
797 * The time when the single largest layout shift contributing to the page's
798 * CLS score occurred.
799 */
800 largestShiftTime?: DOMHighResTimeStamp;
801 /**
802 * The layout shift score of the single largest layout shift contributing to
803 * the page's CLS score.
804 */
805 largestShiftValue?: number;
806 /**
807 * The `LayoutShiftEntry` representing the single largest layout shift
808 * contributing to the page's CLS score. (Useful when you need more than just
809 * `largestShiftTarget`, `largestShiftTime`, and `largestShiftValue`).
810 */
811 largestShiftEntry?: LayoutShift;
812 /**
813 * The first element source (in document order) among the `sources` list
814 * of the `largestShiftEntry` object. (Also useful when you need more than
815 * just `largestShiftTarget`, `largestShiftTime`, and `largestShiftValue`).
816 */
817 largestShiftSource?: LayoutShiftAttribution;
818 /**
819 * The loading state of the document at the time when the largest layout
820 * shift contribution to the page's CLS score occurred (see `LoadState`
821 * for details).
822 */
823 loadState?: LoadState;
824}
825```
826
827#### `FCPAttribution`
828
829```ts
830interface FCPAttribution {
831 /**
832 * The time from when the user initiates loading the page until when the
833 * browser receives the first byte of the response (a.k.a. TTFB).
834 */
835 timeToFirstByte: number;
836 /**
837 * The delta between TTFB and the first contentful paint (FCP).
838 */
839 firstByteToFCP: number;
840 /**
841 * The loading state of the document at the time when FCP `occurred (see
842 * `LoadState` for details). Ideally, documents can paint before they finish
843 * loading (e.g. the `loading` or `dom-interactive` phases).
844 */
845 loadState: LoadState;
846 /**
847 * The `PerformancePaintTiming` entry corresponding to FCP.
848 */
849 fcpEntry?: PerformancePaintTiming;
850 /**
851 * The `navigation` entry of the current page, which is useful for diagnosing
852 * general page load issues. This can be used to access `serverTiming` for example:
853 * navigationEntry?.serverTiming
854 */
855 navigationEntry?: PerformanceNavigationTiming;
856}
857```
858
859#### `FIDAttribution`
860
861_This interface is deprecated and will be removed in next major release_
862
863```ts
864interface FIDAttribution {
865 /**
866 * A selector identifying the element that the user interacted with. This
867 * element will be the `target` of the `event` dispatched.
868 */
869 eventTarget: string;
870 /**
871 * The time when the user interacted. This time will match the `timeStamp`
872 * value of the `event` dispatched.
873 */
874 eventTime: number;
875 /**
876 * The `type` of the `event` dispatched from the user interaction.
877 */
878 eventType: string;
879 /**
880 * The `PerformanceEventTiming` entry corresponding to FID.
881 */
882 eventEntry: PerformanceEventTiming;
883 /**
884 * The loading state of the document at the time when the first interaction
885 * occurred (see `LoadState` for details). If the first interaction occurred
886 * while the document was loading and executing script (e.g. usually in the
887 * `dom-interactive` phase) it can result in long input delays.
888 */
889 loadState: LoadState;
890}
891```
892
893#### `INPAttribution`
894
895```ts
896interface INPAttribution {
897 /**
898 * A selector identifying the element that the user first interacted with
899 * as part of the frame where the INP candidate interaction occurred.
900 * If this value is an empty string, that generally means the element was
901 * removed from the DOM after the interaction.
902 */
903 interactionTarget: string;
904 /**
905 * A reference to the HTML element identified by `interactionTarget`.
906 * NOTE: for attribution purpose, a selector identifying the element is
907 * typically more useful than the element itself. However, the element is
908 * also made available in case additional context is needed.
909 */
910 interactionTargetElement: Node | undefined;
911 /**
912 * The time when the user first interacted during the frame where the INP
913 * candidate interaction occurred (if more than one interaction occurred
914 * within the frame, only the first time is reported).
915 */
916 interactionTime: DOMHighResTimeStamp;
917 /**
918 * The best-guess timestamp of the next paint after the interaction.
919 * In general, this timestamp is the same as the `startTime + duration` of
920 * the event timing entry. However, since `duration` values are rounded to
921 * the nearest 8ms, it can sometimes appear that the paint occurred before
922 * processing ended (which cannot happen). This value clamps the paint time
923 * so it's always after `processingEnd` from the Event Timing API and
924 * `renderStart` from the Long Animation Frame API (where available).
925 * It also averages the duration values for all entries in the same
926 * animation frame, which should be closer to the "real" value.
927 */
928 nextPaintTime: DOMHighResTimeStamp;
929 /**
930 * The type of interaction, based on the event type of the `event` entry
931 * that corresponds to the interaction (i.e. the first `event` entry
932 * containing an `interactionId` dispatched in a given animation frame).
933 * For "pointerdown", "pointerup", or "click" events this will be "pointer",
934 * and for "keydown" or "keyup" events this will be "keyboard".
935 */
936 interactionType: 'pointer' | 'keyboard';
937 /**
938 * An array of Event Timing entries that were processed within the same
939 * animation frame as the INP candidate interaction.
940 */
941 processedEventEntries: PerformanceEventTiming[];
942 /**
943 * If the browser supports the Long Animation Frame API, this array will
944 * include any `long-animation-frame` entries that intersect with the INP
945 * candidate interaction's `startTime` and the `processingEnd` time of the
946 * last event processed within that animation frame. If the browser does not
947 * support the Long Animation Frame API or no `long-animation-frame` entries
948 * are detect, this array will be empty.
949 */
950 longAnimationFrameEntries: PerformanceLongAnimationFrameTiming[];
951 /**
952 * The time from when the user interacted with the page until when the
953 * browser was first able to start processing event listeners for that
954 * interaction. This time captures the delay before event processing can
955 * begin due to the main thread being busy with other work.
956 */
957 inputDelay: number;
958 /**
959 * The time from when the first event listener started running in response to
960 * the user interaction until when all event listener processing has finished.
961 */
962 processingDuration: number;
963 /**
964 * The time from when the browser finished processing all event listeners for
965 * the user interaction until the next frame is presented on the screen and
966 * visible to the user. This time includes work on the main thread (such as
967 * `requestAnimationFrame()` callbacks, `ResizeObserver` and
968 * `IntersectionObserver` callbacks, and style/layout calculation) as well
969 * as off-main-thread work (such as compositor, GPU, and raster work).
970 */
971 presentationDelay: number;
972 /**
973 * The loading state of the document at the time when the interaction
974 * corresponding to INP occurred (see `LoadState` for details). If the
975 * interaction occurred while the document was loading and executing script
976 * (e.g. usually in the `dom-interactive` phase) it can result in long delays.
977 */
978 loadState: LoadState;
979}
980```
981
982#### `LCPAttribution`
983
984```ts
985interface LCPAttribution {
986 /**
987 * The element corresponding to the largest contentful paint for the page.
988 */
989 element?: string;
990 /**
991 * The URL (if applicable) of the LCP image resource. If the LCP element
992 * is a text node, this value will not be set.
993 */
994 url?: string;
995 /**
996 * The time from when the user initiates loading the page until when the
997 * browser receives the first byte of the response (a.k.a. TTFB). See
998 * [Optimize LCP](https://web.dev/articles/optimize-lcp) for details.
999 */
1000 timeToFirstByte: number;
1001 /**
1002 * The delta between TTFB and when the browser starts loading the LCP
1003 * resource (if there is one, otherwise 0). See [Optimize
1004 * LCP](https://web.dev/articles/optimize-lcp) for details.
1005 */
1006 resourceLoadDelay: number;
1007 /**
1008 * The total time it takes to load the LCP resource itself (if there is one,
1009 * otherwise 0). See [Optimize LCP](https://web.dev/articles/optimize-lcp) for
1010 * details.
1011 */
1012 resourceLoadDuration: number;
1013 /**
1014 * The delta between when the LCP resource finishes loading until the LCP
1015 * element is fully rendered. See [Optimize
1016 * LCP](https://web.dev/articles/optimize-lcp) for details.
1017 */
1018 elementRenderDelay: number;
1019 /**
1020 * The `navigation` entry of the current page, which is useful for diagnosing
1021 * general page load issues. This can be used to access `serverTiming` for example:
1022 * navigationEntry?.serverTiming
1023 */
1024 navigationEntry?: PerformanceNavigationTiming;
1025 /**
1026 * The `resource` entry for the LCP resource (if applicable), which is useful
1027 * for diagnosing resource load issues.
1028 */
1029 lcpResourceEntry?: PerformanceResourceTiming;
1030 /**
1031 * The `LargestContentfulPaint` entry corresponding to LCP.
1032 */
1033 lcpEntry?: LargestContentfulPaint;
1034}
1035```
1036
1037#### `TTFBAttribution`
1038
1039```ts
1040export interface TTFBAttribution {
1041 /**
1042 * The total time from when the user initiates loading the page to when the
1043 * page starts to handle the request. Large values here are typically due
1044 * to HTTP redirects, though other browser processing contributes to this
1045 * duration as well (so even without redirect it's generally not zero).
1046 */
1047 waitingDuration: number;
1048 /**
1049 * The total time spent checking the HTTP cache for a match. For navigations
1050 * handled via service worker, this duration usually includes service worker
1051 * start-up time as well as time processing `fetch` event listeners, with
1052 * some exceptions, see: https://github.com/w3c/navigation-timing/issues/199
1053 */
1054 cacheDuration: number;
1055 /**
1056 * The total time to resolve the DNS for the requested domain.
1057 */
1058 dnsDuration: number;
1059 /**
1060 * The total time to create the connection to the requested domain.
1061 */
1062 connectionDuration: number;
1063 /**
1064 * The total time from when the request was sent until the first byte of the
1065 * response was received. This includes network time as well as server
1066 * processing time.
1067 */
1068 requestDuration: number;
1069 /**
1070 * The `navigation` entry of the current page, which is useful for diagnosing
1071 * general page load issues. This can be used to access `serverTiming` for
1072 * example: navigationEntry?.serverTiming
1073 */
1074 navigationEntry?: PerformanceNavigationTiming;
1075}
1076```
1077
1078## Browser Support
1079
1080The `web-vitals` code has been tested and will run without error in all major browsers as well as Internet Explorer back to version 9. However, some of the APIs required to capture these metrics are currently only available in Chromium-based browsers (e.g. Chrome, Edge, Opera, Samsung Internet).
1081
1082Browser support for each function is as follows:
1083
1084- `onCLS()`: Chromium
1085- `onFCP()`: Chromium, Firefox, Safari
1086- `onFID()`: Chromium, Firefox _(Deprecated)_
1087- `onINP()`: Chromium
1088- `onLCP()`: Chromium, Firefox
1089- `onTTFB()`: Chromium, Firefox, Safari
1090
1091## Limitations
1092
1093The `web-vitals` library is primarily a wrapper around the Web APIs that measure the Web Vitals metrics, which means the limitations of those APIs will mostly apply to this library as well. More details on these limitations is available in [this blog post](https://web.dev/articles/crux-and-rum-differences).
1094
1095The primary limitation of these APIs is they have no visibility into `<iframe>` content (not even same-origin iframes), which means pages that make use of iframes will likely see a difference between the data measured by this library and the data available in the Chrome User Experience Report (which does include iframe content).
1096
1097For same-origin iframes, it's possible to use the `web-vitals` library to measure metrics, but it's tricky because it requires the developer to add the library to every frame and `postMessage()` the results to the parent frame for aggregation.
1098
1099_**Note:** given the lack of iframe support, the `onCLS()` function technically measures [DCLS](https://github.com/wicg/layout-instability#cumulative-scores) (Document Cumulative Layout Shift) rather than CLS, if the page includes iframes)._
1100
1101## Development
1102
1103### Building the code
1104
1105The `web-vitals` source code is written in TypeScript. To transpile the code and build the production bundles, run the following command.
1106
1107```sh
1108npm run build
1109```
1110
1111To build the code and watch for changes, run:
1112
1113```sh
1114npm run watch
1115```
1116
1117### Running the tests
1118
1119The `web-vitals` code is tested in real browsers using [webdriver.io](https://webdriver.io/). Use the following command to run the tests:
1120
1121```sh
1122npm test
1123```
1124
1125To test any of the APIs manually, you can start the test server
1126
1127```sh
1128npm run test:server
1129```
1130
1131Then navigate to `http://localhost:9090/test/<view>`, where `<view>` is the basename of one the templates under [/test/views/](/test/views/).
1132
1133You'll likely want to combine this with `npm run watch` to ensure any changes you make are transpiled and rebuilt.
1134
1135## Integrations
1136
1137- [**Web Vitals Connector**](https://goo.gle/web-vitals-connector): Data Studio connector to create dashboards from [Web Vitals data captured in BiqQuery](https://web.dev/articles/vitals-ga4).
1138- [**Core Web Vitals Custom Tag template**](https://www.simoahava.com/custom-templates/core-web-vitals/): Custom GTM template tag to [add measurement handlers](https://www.simoahava.com/analytics/track-core-web-vitals-in-ga4-with-google-tag-manager/) for all Core Web Vitals metrics.
1139- [**`web-vitals-reporter`**](https://github.com/treosh/web-vitals-reporter): JavaScript library to batch `callback` functions and send data with a single request.
1140
1141## License
1142
1143[Apache 2.0](/LICENSE)