web-vitals

  • Version 5.0.3
  • Published
  • 378 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 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 onINP

onINP: (onReport: (metric: INPMetric) => void, opts?: INPReportOpts) => 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 will not be reported. To avoid reporting no interactions in these cases, the library will fall back to the input delay of the first interaction. 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 AttributionReportOpts

interface AttributionReportOpts extends ReportOpts {}

    property generateTarget

    generateTarget?: (el: Node | null) => string;

      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;
      • By default, a selector identifying the first element (in document order) that shifted when the single largest layout shift that contributed to the page's CLS score occurred. If the generateTarget configuration option was passed, then this will instead be the return value of that function.

      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 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;
                      • By default, 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. If the generateTarget configuration option was passed, then this will instead be the return value of that function.

                      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 detected, this array will be empty.

                      property longestScript

                      longestScript?: INPLongestScriptSummary;
                      • Summary information about the longest script entry intersecting the INP duration. Note, only script entries above 5 milliseconds are reported by the Long Animation Frame API.

                      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 (and can be rounded down), this value is clamped to always be reported after the processing times.

                      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.

                      property totalPaintDuration

                      totalPaintDuration?: number;
                      • The off main-thread presentation delay from the end of the last Long Animation Frame (where available) until the INP end point.

                      property totalScriptDuration

                      totalScriptDuration?: number;
                      • The total duration of Long Animation Frame scripts that intersect the INP duration excluding any forced style and layout (that is included in totalStyleAndLayout). Note, this is limited to scripts > 5 milliseconds.

                      property totalStyleAndLayoutDuration

                      totalStyleAndLayoutDuration?: number;
                      • The total style and layout duration from any Long Animation Frames intersecting the INP interaction. This includes any end-of-frame style and layout duration + any forced style and layout duration.

                      property totalUnattributedDuration

                      totalUnattributedDuration?: number;
                      • The total unattributed time not included in any of the previous totals. This includes scripts < 5 milliseconds and other timings not attributed by Long Animation Frame (including when a frame is < 50ms and so has no Long Animation Frame). When no Long Animation Frames are present this will be undefined, rather than everything being unattributed to make it clearer when it's expected to be small.

                      interface INPAttributionReportOpts

                      interface INPAttributionReportOpts extends AttributionReportOpts {}

                        property durationThreshold

                        durationThreshold?: number;

                          interface INPLongestScriptSummary

                          interface INPLongestScriptSummary {}

                            property entry

                            entry: PerformanceScriptTiming;
                            • The longest Long Animation Frame script entry that intersects the INP interaction.

                            property intersectingDuration

                            intersectingDuration: number;
                            • The amount of time the longest script intersected the INP duration.

                            property subpart

                            subpart: 'input-delay' | 'processing-duration' | 'presentation-delay';
                            • The INP subpart where the longest script ran.

                            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 INPReportOpts

                                  interface INPReportOpts extends ReportOpts {}

                                    property durationThreshold

                                    durationThreshold?: number;

                                      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 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 target

                                      target?: string;
                                      • By default, a selector identifying the element corresponding to the largest contentful paint for the page. If the generateTarget configuration option was passed, then this will instead be the return value of that function.

                                      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' | '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 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 | INPMetric | LCPMetric | TTFBMetric;
                                                            • The union of supported metric types.

                                                            type MetricWithAttribution

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

                                                            Package Files (13)

                                                            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>