Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active October 20, 2023 12:24
Show Gist options
  • Save samarpanda/a286aa9b91c0919984c4de3391a8876f to your computer and use it in GitHub Desktop.
Save samarpanda/a286aa9b91c0919984c4de3391a8876f to your computer and use it in GitHub Desktop.
First input delay (FID)

First input delay(FID)

This is an interactive metric. Collected once user tries to interact with the page.

Using web-vitals npm package

import {getFID} from 'web-vitals';
getFID(console.log);

Tracking fid value

let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
document.addEventListener('visibilitychange', (event) => {
  firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
}, {once: true});

// Sends the passed data to an analytics endpoint. This code
// uses `/analytics`; you can replace it with your own URL.
function sendToAnalytics(data) {
  const body = JSON.stringify(data);
  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
  (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
      fetch('/analytics', {body, method: 'POST', keepalive: true});
}

// Use a try/catch instead of feature detecting `first-input`
// support, since some browsers throw when using the new `type` option.
// https://bugs.webkit.org/show_bug.cgi?id=209216
try {
  function onFirstInputEntry(entry, po) {
    // Only report FID if the page wasn't hidden prior to
    // the entry being dispatched. This typically happens when a
    // page is loaded in a background tab.
    if (entry.startTime < firstHiddenTime) {
      const fid = entry.processingStart - entry.startTime;

      // Disconnect the observer.
      po.disconnect();

      // Report the FID value to an analytics endpoint.
      sendToAnalytics({fid});
    }
  }

  // Create a PerformanceObserver that calls `onFirstInputEntry` for each entry.
  const po = new PerformanceObserver((entryList, po) => {
    entryList.getEntries().forEach((entry) => onFirstInputEntry(entry, po));
  });

  // Observe entries of type `first-input`, including buffered entries,
  // i.e. entries that occurred before calling `observe()` below.
  po.observe({
    type: 'first-input',
    buffered: true,
  });
} catch (e) {
  // Do nothing if the browser doesn't support this API.
}

credits to web.dev/fid

@samarpanda
Copy link
Author

let fid;
var fidObserver = new PerformanceObserver(function handleFID(entryList) {
    var entries = entryList.getEntries() || [];
    entries.forEach(function(entry) {
      fid = entry.processingStart - entry.startTime;
      console.log("Recorded FID Performance: " + fid);
    });
  }).observe({ type: "first-input", buffered: true });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment