web-vitals

  • Version 4.2.3
  • Published
  • 387 kB
  • No dependencies
  • Apache-2.0 license

Install

npm i web-vitals
yarn add web-vitals
pnpm add web-vitals

Overview

Easily measure performance metrics in JavaScript

Index

Variables

variable CLSThresholds

const CLSThresholds: MetricRatingThresholds;
  • Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score

variable FCPThresholds

const FCPThresholds: MetricRatingThresholds;
  • Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score

variable FIDThresholds

const FIDThresholds: MetricRatingThresholds;
  • Thresholds for FID. See https://web.dev/articles/fid#what_is_a_good_fid_score

variable INPThresholds

const INPThresholds: MetricRatingThresholds;
  • Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score

variable LCPThresholds

const LCPThresholds: MetricRatingThresholds;
  • Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score

variable TTFBThresholds

const TTFBThresholds: MetricRatingThresholds;
  • Thresholds for TTFB. See https://web.dev/articles/ttfb#what_is_a_good_ttfb_score

Functions

function onCLS

onCLS: (onReport: (metric: CLSMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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 (corresponding to a [layout shift score](https://web.dev/articles/cls#layout_shift_score)).

    If the reportAllChanges configuration option 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.

    _**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._

function onFCP

onFCP: (onReport: (metric: FCPMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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.

function onFID

onFID: (onReport: (metric: FIDMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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.

    _**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._

function onINP

onINP: (onReport: (metric: INPMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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.

    A custom durationThreshold configuration option 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).

    If the reportAllChanges configuration option 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.

    _**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._

function onLCP

onLCP: (onReport: (metric: LCPMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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.

    If the reportAllChanges configuration option 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.

function onTTFB

onTTFB: (onReport: (metric: TTFBMetric) => void, opts?: ReportOpts) => void;
  • Calculates 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.

    Note, 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/). For 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.

Interfaces

interface CLSAttribution

interface CLSAttribution {}
  • An object containing potentially-helpful debugging information that can be sent along with the CLS value for the current page visit in order to help identify issues happening to real-users in the field.

property largestShiftEntry

largestShiftEntry?: LayoutShift;
  • The LayoutShiftEntry representing the single largest layout shift contributing to the page's CLS score. (Useful when you need more than just largestShiftTarget, largestShiftTime, and largestShiftValue).

property largestShiftSource

largestShiftSource?: LayoutShiftAttribution;
  • The first element source (in document order) among the sources list of the largestShiftEntry object. (Also useful when you need more than just largestShiftTarget, largestShiftTime, and largestShiftValue).

property largestShiftTarget

largestShiftTarget?: string;
  • A selector identifying the first element (in document order) that shifted when the single largest layout shift contributing to the page's CLS score occurred.

property largestShiftTime

largestShiftTime?: DOMHighResTimeStamp;
  • The time when the single largest layout shift contributing to the page's CLS score occurred.

property largestShiftValue

largestShiftValue?: number;
  • The layout shift score of the single largest layout shift contributing to the page's CLS score.

property loadState

loadState?: LoadState;
  • The loading state of the document at the time when the largest layout shift contribution to the page's CLS score occurred (see LoadState for details).

interface CLSMetric

interface CLSMetric extends Metric {}
  • A CLS-specific version of the Metric object.

property entries

entries: LayoutShift[];

    property name

    name: 'CLS';

      interface CLSMetricWithAttribution

      interface CLSMetricWithAttribution extends CLSMetric {}
      • A CLS-specific version of the Metric object with attribution.

      property attribution

      attribution: CLSAttribution;

        interface FCPAttribution

        interface FCPAttribution {}
        • An object containing potentially-helpful debugging information that can be sent along with the FCP value for the current page visit in order to help identify issues happening to real-users in the field.

        property fcpEntry

        fcpEntry?: PerformancePaintTiming;
        • The PerformancePaintTiming entry corresponding to FCP.

        property firstByteToFCP

        firstByteToFCP: number;
        • The delta between TTFB and the first contentful paint (FCP).

        property loadState

        loadState: LoadState;
        • The loading state of the document at the time when FCP `occurred (see LoadState for details). Ideally, documents can paint before they finish loading (e.g. the loading or dom-interactive phases).

        property navigationEntry

        navigationEntry?: PerformanceNavigationTiming;
        • The navigation entry of the current page, which is useful for diagnosing general page load issues. This can be used to access serverTiming for example: navigationEntry?.serverTiming

        property timeToFirstByte

        timeToFirstByte: number;
        • The time from when the user initiates loading the page until when the browser receives the first byte of the response (a.k.a. TTFB).

        interface FCPMetric

        interface FCPMetric extends Metric {}
        • An FCP-specific version of the Metric object.

        property entries

        entries: PerformancePaintTiming[];

          property name

          name: 'FCP';

            interface FCPMetricWithAttribution

            interface FCPMetricWithAttribution extends FCPMetric {}
            • An FCP-specific version of the Metric object with attribution.

            property attribution

            attribution: FCPAttribution;

              interface FIDAttribution

              interface FIDAttribution {}
              • An object containing potentially-helpful debugging information that can be sent along with the FID value for the current page visit in order to help identify issues happening to real-users in the field.

              property eventEntry

              eventEntry: PerformanceEventTiming;
              • The PerformanceEventTiming entry corresponding to FID.

              property eventTarget

              eventTarget: string;
              • A selector identifying the element that the user interacted with. This element will be the target of the event dispatched.

              property eventTime

              eventTime: number;
              • The time when the user interacted. This time will match the timeStamp value of the event dispatched.

              property eventType

              eventType: string;
              • The type of the event dispatched from the user interaction.

              property loadState

              loadState: LoadState;
              • The loading state of the document at the time when the first interaction occurred (see LoadState for details). If the first interaction occurred while the document was loading and executing script (e.g. usually in the dom-interactive phase) it can result in long input delays.

              interface FIDMetric

              interface FIDMetric extends Metric {}
              • An FID-specific version of the Metric object.

              property entries

              entries: PerformanceEventTiming[];

                property name

                name: 'FID';

                  interface FIDMetricWithAttribution

                  interface FIDMetricWithAttribution extends FIDMetric {}
                  • An FID-specific version of the Metric object with attribution.

                  property attribution

                  attribution: FIDAttribution;

                    interface FirstInputPolyfillCallback

                    interface FirstInputPolyfillCallback {}

                      call signature

                      (entry: FirstInputPolyfillEntry): void;

                        interface INPAttribution

                        interface INPAttribution {}
                        • An object containing potentially-helpful debugging information that can be sent along with the INP value for the current page visit in order to help identify issues happening to real-users in the field.

                        property inputDelay

                        inputDelay: number;
                        • The time from when the user interacted with the page until when the browser was first able to start processing event listeners for that interaction. This time captures the delay before event processing can begin due to the main thread being busy with other work.

                        property interactionTarget

                        interactionTarget: string;
                        • A selector identifying the element that the user first interacted with as part of the frame where the INP candidate interaction occurred. If this value is an empty string, that generally means the element was removed from the DOM after the interaction.

                        property interactionTargetElement

                        interactionTargetElement: Node | undefined;
                        • A reference to the HTML element identified by interactionTargetSelector. NOTE: for attribution purpose, a selector identifying the element is typically more useful than the element itself. However, the element is also made available in case additional context is needed.

                        property interactionTime

                        interactionTime: DOMHighResTimeStamp;
                        • The time when the user first interacted during the frame where the INP candidate interaction occurred (if more than one interaction occurred within the frame, only the first time is reported).

                        property interactionType

                        interactionType: 'pointer' | 'keyboard';
                        • The type of interaction, based on the event type of the event entry that corresponds to the interaction (i.e. the first event entry containing an interactionId dispatched in a given animation frame). For "pointerdown", "pointerup", or "click" events this will be "pointer", and for "keydown" or "keyup" events this will be "keyboard".

                        property loadState

                        loadState: LoadState;
                        • The loading state of the document at the time when the interaction corresponding to INP occurred (see LoadState for details). If the interaction occurred while the document was loading and executing script (e.g. usually in the dom-interactive phase) it can result in long delays.

                        property longAnimationFrameEntries

                        longAnimationFrameEntries: PerformanceLongAnimationFrameTiming[];
                        • If the browser supports the Long Animation Frame API, this array will include any long-animation-frame entries that intersect with the INP candidate interaction's startTime and the processingEnd time of the last event processed within that animation frame. If the browser does not support the Long Animation Frame API or no long-animation-frame entries are detect, this array will be empty.

                        property nextPaintTime

                        nextPaintTime: DOMHighResTimeStamp;
                        • The best-guess timestamp of the next paint after the interaction. In general, this timestamp is the same as the startTime + duration of the event timing entry. However, since duration values are rounded to the nearest 8ms, it can sometimes appear that the paint occurred before processing ended (which cannot happen). This value clamps the paint time so it's always after processingEnd from the Event Timing API and renderStart from the Long Animation Frame API (where available). It also averages the duration values for all entries in the same animation frame, which should be closer to the "real" value.

                        property presentationDelay

                        presentationDelay: number;
                        • The time from when the browser finished processing all event listeners for the user interaction until the next frame is presented on the screen and visible to the user. This time includes work on the main thread (such as requestAnimationFrame() callbacks, ResizeObserver and IntersectionObserver callbacks, and style/layout calculation) as well as off-main-thread work (such as compositor, GPU, and raster work).

                        property processedEventEntries

                        processedEventEntries: PerformanceEventTiming[];
                        • An array of Event Timing entries that were processed within the same animation frame as the INP candidate interaction.

                        property processingDuration

                        processingDuration: number;
                        • The time from when the first event listener started running in response to the user interaction until when all event listener processing has finished.

                        interface INPMetric

                        interface INPMetric extends Metric {}
                        • An INP-specific version of the Metric object.

                        property entries

                        entries: PerformanceEventTiming[];

                          property name

                          name: 'INP';

                            interface INPMetricWithAttribution

                            interface INPMetricWithAttribution extends INPMetric {}
                            • An INP-specific version of the Metric object with attribution.

                            property attribution

                            attribution: INPAttribution;

                              interface LCPAttribution

                              interface LCPAttribution {}
                              • An object containing potentially-helpful debugging information that can be sent along with the LCP value for the current page visit in order to help identify issues happening to real-users in the field.

                              property element

                              element?: string;
                              • The element corresponding to the largest contentful paint for the page.

                              property elementRenderDelay

                              elementRenderDelay: number;
                              • The delta between when the LCP resource finishes loading until the LCP element is fully rendered. See [Optimize LCP](https://web.dev/articles/optimize-lcp) for details.

                              property lcpEntry

                              lcpEntry?: LargestContentfulPaint;
                              • The LargestContentfulPaint entry corresponding to LCP.

                              property lcpResourceEntry

                              lcpResourceEntry?: PerformanceResourceTiming;
                              • The resource entry for the LCP resource (if applicable), which is useful for diagnosing resource load issues.

                              property navigationEntry

                              navigationEntry?: PerformanceNavigationTiming;
                              • The navigation entry of the current page, which is useful for diagnosing general page load issues. This can be used to access serverTiming for example: navigationEntry?.serverTiming

                              property resourceLoadDelay

                              resourceLoadDelay: number;
                              • The delta between TTFB and when the browser starts loading the LCP resource (if there is one, otherwise 0). See [Optimize LCP](https://web.dev/articles/optimize-lcp) for details.

                              property resourceLoadDuration

                              resourceLoadDuration: number;
                              • The total time it takes to load the LCP resource itself (if there is one, otherwise 0). See [Optimize LCP](https://web.dev/articles/optimize-lcp) for details.

                              property timeToFirstByte

                              timeToFirstByte: number;
                              • The time from when the user initiates loading the page until when the browser receives the first byte of the response (a.k.a. TTFB). See [Optimize LCP](https://web.dev/articles/optimize-lcp) for details.

                              property url

                              url?: string;
                              • The URL (if applicable) of the LCP image resource. If the LCP element is a text node, this value will not be set.

                              interface LCPMetric

                              interface LCPMetric extends Metric {}
                              • An LCP-specific version of the Metric object.

                              property entries

                              entries: LargestContentfulPaint[];

                                property name

                                name: 'LCP';

                                  interface LCPMetricWithAttribution

                                  interface LCPMetricWithAttribution extends LCPMetric {}
                                  • An LCP-specific version of the Metric object with attribution.

                                  property attribution

                                  attribution: LCPAttribution;

                                    interface Metric

                                    interface Metric {}

                                      property delta

                                      delta: number;
                                      • The delta between the current value and the last-reported value. On the first report, delta and value will always be the same.

                                      property entries

                                      entries: PerformanceEntry[];
                                      • Any performance entries relevant to the metric value calculation. The array may also be empty if the metric value was not based on any entries (e.g. a CLS value of 0 given no layout shifts).

                                      property id

                                      id: string;
                                      • A unique ID representing this particular metric instance. This ID can be used by an analytics tool to dedupe multiple values sent for the same metric instance, or to group multiple deltas together and calculate a total. It can also be used to differentiate multiple different metric instances sent from the same page, which can happen if the page is restored from the back/forward cache (in that case new metrics object get created).

                                      property name

                                      name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';
                                      • The name of the metric (in acronym form).

                                      property navigationType

                                      navigationType:
                                      | 'navigate'
                                      | 'reload'
                                      | 'back-forward'
                                      | 'back-forward-cache'
                                      | 'prerender'
                                      | 'restore';
                                      • The type of navigation.

                                        This will be the value returned by the Navigation Timing API (or undefined if the browser doesn't support that API), with the following exceptions: - 'back-forward-cache': for pages that are restored from the bfcache. - 'back_forward' is renamed to 'back-forward' for consistency. - 'prerender': for pages that were prerendered. - 'restore': for pages that were discarded by the browser and then restored by the user.

                                      property rating

                                      rating: 'good' | 'needs-improvement' | 'poor';
                                      • The rating as to whether the metric value is within the "good", "needs improvement", or "poor" thresholds of the metric.

                                      property value

                                      value: number;
                                      • The current value of the metric.

                                      interface ReportCallback

                                      interface ReportCallback {}
                                      • Deprecated

                                        Use metric-specific function types instead, such as: (metric: LCPMetric) => void. If a single callback type is needed for multiple metrics, use (metric: MetricType) => void.

                                      call signature

                                      (metric: MetricType): void;

                                        interface ReportOpts

                                        interface ReportOpts {}

                                          property durationThreshold

                                          durationThreshold?: number;

                                            property reportAllChanges

                                            reportAllChanges?: boolean;

                                              interface TTFBAttribution

                                              interface TTFBAttribution {}
                                              • An object containing potentially-helpful debugging information that can be sent along with the TTFB value for the current page visit in order to help identify issues happening to real-users in the field.

                                                NOTE: these values are primarily useful for page loads not handled via service worker, as browsers differ in what they report when service worker is involved, see: https://github.com/w3c/navigation-timing/issues/199

                                              property cacheDuration

                                              cacheDuration: number;
                                              • The total time spent checking the HTTP cache for a match. For navigations handled via service worker, this duration usually includes service worker start-up time as well as time processing fetch event listeners, with some exceptions, see: https://github.com/w3c/navigation-timing/issues/199

                                              property connectionDuration

                                              connectionDuration: number;
                                              • The total time to create the connection to the requested domain.

                                              property dnsDuration

                                              dnsDuration: number;
                                              • The total time to resolve the DNS for the requested domain.

                                              property navigationEntry

                                              navigationEntry?: PerformanceNavigationTiming;
                                              • The navigation entry of the current page, which is useful for diagnosing general page load issues. This can be used to access serverTiming for example: navigationEntry?.serverTiming

                                              property requestDuration

                                              requestDuration: number;
                                              • The total time from when the request was sent until the first byte of the response was received. This includes network time as well as server processing time.

                                              property waitingDuration

                                              waitingDuration: number;
                                              • The total time from when the user initiates loading the page to when the page starts to handle the request. Large values here are typically due to HTTP redirects, though other browser processing contributes to this duration as well (so even without redirect it's generally not zero).

                                              interface TTFBMetric

                                              interface TTFBMetric extends Metric {}
                                              • A TTFB-specific version of the Metric object.

                                              property entries

                                              entries: PerformanceNavigationTiming[];

                                                property name

                                                name: 'TTFB';

                                                  interface TTFBMetricWithAttribution

                                                  interface TTFBMetricWithAttribution extends TTFBMetric {}
                                                  • A TTFB-specific version of the Metric object with attribution.

                                                  property attribution

                                                  attribution: TTFBAttribution;

                                                    Type Aliases

                                                    type FirstInputPolyfillEntry

                                                    type FirstInputPolyfillEntry = Omit<PerformanceEventTiming, 'processingEnd'>;

                                                      type LoadState

                                                      type LoadState = 'loading' | 'dom-interactive' | 'dom-content-loaded' | 'complete';
                                                      • The loading state of the document. Note: this value is similar to document.readyState but it subdivides the "interactive" state into the time before and after the DOMContentLoaded event fires.

                                                        State descriptions: - loading: the initial document response has not yet been fully downloaded and parsed. This is equivalent to the corresponding readyState value. - dom-interactive: the document has been fully loaded and parsed, but scripts may not have yet finished loading and executing. - dom-content-loaded: the document is fully loaded and parsed, and all scripts (except async scripts) have loaded and finished executing. - complete: the document and all of its sub-resources have finished loading. This is equivalent to the corresponding readyState value.

                                                      type MetricRatingThresholds

                                                      type MetricRatingThresholds = [number, number];
                                                      • The thresholds of metric's "good", "needs improvement", and "poor" ratings.

                                                        - Metric values up to and including [0] are rated "good" - Metric values up to and including [1] are rated "needs improvement" - Metric values above [1] are "poor"

                                                        | Metric value | Rating | | --------------- | ------------------- | | ≦ [0] | "good" | | > [0] and ≦ [1] | "needs improvement" | | > [1] | "poor" |

                                                      type MetricType

                                                      type MetricType =
                                                      | CLSMetric
                                                      | FCPMetric
                                                      | FIDMetric
                                                      | INPMetric
                                                      | LCPMetric
                                                      | TTFBMetric;
                                                      • The union of supported metric types.

                                                      type MetricWithAttribution

                                                      type MetricWithAttribution =
                                                      | CLSMetricWithAttribution
                                                      | FCPMetricWithAttribution
                                                      | FIDMetricWithAttribution
                                                      | INPMetricWithAttribution
                                                      | LCPMetricWithAttribution
                                                      | TTFBMetricWithAttribution;
                                                      • The union of supported metric attribution types.

                                                      Package Files (15)

                                                      Dependencies (0)

                                                      No dependencies.

                                                      Dev Dependencies (26)

                                                      Peer Dependencies (0)

                                                      No peer dependencies.

                                                      Badge

                                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/web-vitals.

                                                      • Markdown
                                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/web-vitals)
                                                      • HTML
                                                        <a href="https://www.jsdocs.io/package/web-vitals"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>