What is First Input Delay?

What is First Input Delay (FID), And How To Optimize It?

22 Sep 2020

quick summary

First Input Delay is a great metric to track and improve on your page. It allows you to address the feeling of clunkiness your users may experience while your page is loading. Improving it is also bound to positively impact various other aspects of your web performance.

What is First Input Delay?

First Input Delay (FID) is a real-user web performance metric that tracks the time from when a user first interacts with a web page after entering it to the time when the browser can start processing that interaction – when the browser’s main thread is idle.

To put it in simpler terms, FID is the delay between when you click or tap on something like a link or a button, and the time that the browser responds to your action and starts processing it. 

First Input Delay is measured in milliseconds (ms).

The events that count as user interactions measured by FID must be discrete (finite). Continuous types of user interaction, like zooming or scrolling the page, can’t be properly measured using this metric. They often don’t run on the browser’s main thread and have different constraints.

An example of First Input Delay: the opened page starts loading, the user taps the sidebar to expand it, the browser is still busy loading an image, and once the image is loaded, the browser can process the user input.

FID only measures the first interaction

FID is all about first impressions. The first time a user interacts with your page is fundamental in their experience and perception of your web performance.

Furthermore, most of the blocking of the browser’s main thread occurs in the first moments of a page’s life cycle – that’s when critical resources are being loaded. First Input Delay is a metric that helps you address that and make sure that loading of those critical resources doesn’t make your website feel clunky and irresponsive.

FID measures input delay, not processing

The actual processing or updating of the website as a consequence of that interaction is not measured by FID. That’s because it would be easy for developers to game FID by separating the event handler from the task associated with the event.

How First Input Delay is different from Time to Interactive

Time to Interactive is a very useful performance metric that’s been around for some time now and may seem very similar to First Input Delay.

Time to Interactive (TTI) measures the time it takes for a page to be fully interactive. It’s registered when there’s useful content already rendered on the page (measured by First Contentful Paint), event handlers are registered for most page elements, and user interaction is processed within 50ms.

First Input Delay is different in that it’s able to track user input that happens before the page is fully interactive. For instance, a user may click on a link that appears before event handlers are registered for most page elements. First Input Delay is different from Time to Interactive in that it allows you to capture those early, critical interactions.

Time to Interactive is displayed in Lighthouse.

Time to Interactive is a metric tracked in Lighthouse

Why First Input Delay is a good metric to improve

First Input Delay is one of the most exciting web performance metrics as it is purely a Real User Metric. It cannot be simulated in a lab test – it requires user interaction in order to be measured. FID is all about the actual experience of a user that enters your page. 

For that reason alone, it’s a great metric to monitor and optimize as it defines your website’s User Experience. 

From the SEO standpoint, it’s now official that First Input Delay is about to start influencing your website’s rankings.

First Input Delay is one of the three performance metrics (together with Cumulative Layout Shift and Largest Contentful Paint) that Google wants to promote with its Core Web Vitals initiative. Together, these three metrics accurately track the web performance of user experience.

First Input Delay is the metric that tracks a website’s responsiveness, while CLS tracks visual stability, and LCP tracks loading speed.

Google wants to make Core Web Vitals a part of its ranking algorithm in the near future.

In other words, there’s plenty of reasons to focus on optimizing First Input Delay on your website.

How to measure FID on your page

Tools

The following tools can show you your FID gathered in the field:

Using JavaScript to measure FID

You can also measure FID by adding JavaScript to your page.

There are two ways of doing that:

Add the following code to your page to have FID printed out in the console:

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

If you don’t want to import the web-vitals library, you can also use the Event Timing API to manually track FID. 

This code was provided by Philip Walton in his article on FID published on web.dev.


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

function sendToAnalytics(data) {
  const body = JSON.stringify(data);
  (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
      fetch('/analytics', {body, method: 'POST', keepalive: true});
}

try {
  function onFirstInputEntry(entry, po) {
    if (entry.startTime < firstHiddenTime) {
      const fid = entry.processingStart - entry.startTime;
      po.disconnect();
      sendToAnalytics({fid});
    }
  }

  const po = new PerformanceObserver((entryList, po) => {
    entryList.getEntries().forEach((entry) => onFirstInputEntry(entry, po));
  });

  po.observe({
    type: 'first-input',
    buffered: true,
  });
} catch (e) {
}

What’s a good FID score

Studies show that delay of 100ms is perceived as being caused by an associated source. 0.1 second is about the limit for having the user feel that the system is reacting instantaneously.

For these reasons, it’s good to try and keep your FID under 100ms.

This is reflected by FID thresholds in PageSpeed Insights:

  • FID of 100ms or less is considered good,
  • FID of between 100-300ms needs improvement,
  • FID above 300ms is considered poor.

Keep in mind, though, that the browser still needs to run the task associated with the user input, which isn’t measured by FID. So in some cases, your FID might be under 100ms, but the page may still feel a little irresponsive.

Max Potential First Input Delay – the worst-case scenario

First Input Delay can vary heavily depending on when the user first interacts with a page because the browser’s main thread isn’t equally occupied throughout the page’s lifecycle. So some users may experience no delay at all, while others may be strongly discouraged by it, depending on when they first interact with the page.

For that reason, it may be useful to monitor your page’s Max Potential First Input Delay (MPFID)It’s the duration of the longest task run on the main thread after First Contentful Paint is registered.

By measuring the duration of that task, you simulate the potential situation in which the user interacts with the page right just as this long task is starting, and has to wait until it’s completed for the input to be processed.

Optimizing MPFID involves various strategies that reduce the running time of your longest task or break it up into smaller chunks.

MPFID is a lab metric included in Lighthouse. To see it, export the Lighthouse report for your page to a JSON file.

How to emulate FID in the lab

First Input Delay cannot be measured with lab tools like Lighthouse. It requires a real user’s interaction to have an input event to register. However, you can use a different metric that strongly correlates with FID. 

Total Blocking Time (TBT) measures the total amount of time between First Contentful Paint and Time To Interactive when the main thread was blocked from responding to user input.

TBT is a lab metric that you can measure in Lighthouse. If you improve your TBT, you’ll most likely improve your First Input Delay as well.

Total Blocking Time is a metric tracked in Lighthouse

You can also use Time To Interactive as a similar point of reference.

How MercadoLibre used Total Blocking Time to improve First Input Delay

MercadoLibre is a leading e-commerce platform in Latin America. Using Total Blocking Time as a proxy metric, the team at MercadoLibre managed to improve their website’s First Input Delay and overall interactivity.

Since First Input Delay cannot be simulated with a lab test, they used TBT to find long tasks blocking the main thread.

Once they determined which tasks needed shortening, they used techniques such as tree shaking (getting rid of unused yet imported code), deferred hydration and code splitting (splitting code into smaller files) to reduce the size of the code bundles used on the site.

The result was a 90% reduction in Max Potential FID in Lighthouse and a 9% improvement in FID in Chrome User Experience Report.

Optimizing FID

If you’re not satisfied with your FID score, it’s usually an indication that your JavaScript or CSS usage isn’t optimized. 

How to improve FID by optimizing your CSS code

When it comes to CSS files, they need to be downloaded and parsed as soon as possible so that the browser can render the layout of the page. Because of that, your options for reducing the impact of CSS on your First Input Delay are limited. You can refer to the best practices such as minifying and compressing your files or removing unused CSS code.

How to improve FID by optimizing your JavaScript code

JavaScript tasks are usually the culprit when there’s a long input delay. Blocking the browser’s main thread for extended periods of time, they don’t let it process user input.

Below are some strategies you can use to minimize the amount of time the main thread is blocked by JavaScript:

Break up long tasks into smaller, asynchronous tasks.

Long tasks block the main thread not allowing it to process user input. If you break them up into smaller tasks, user input can be processed between them. Try to keep your tasks under 50ms to be safe.

Generate as much content as you can statically, server-side.

Aim to minimize how much data needs to be post-processed on the client-side. That reduces the amount of work that has to be done by the browser to render a page.

Explore the on-demand loading of third-party code.

Third-party code, such as tags or analytics, is often responsible for unnecessarily blocking the main thread. While sometimes analytics need to be loaded at the very start to make sure the whole visit is properly tracked, it’s likely that you’ll find third-party code on your page that doesn’t need to be run right away. Prioritize loading what you believe offers the greatest value to users first. 

Use web workers.

You can delegate some main thread work to web workers to reduce the workload on the main thread. Web workers allow you to delegate some of your JavaScript code to be run on the worker thread, which means less work for the main thread and less input delay.

Defer unused JavaScript.

Use async or defer so JavaScript is executed only when it’s needed. If you’re using modern JS, configure ES6 modules to load on demand.

Minimize unused polyfills.

Polyfills are needed when a user is using an older browser. Developers use them to be able to build websites with modern JavaScript and still deliver all functionalities to the browsers that don’t support some of the modern features.

Make sure that polyfills are not run if they are not needed. Deliver separate bundles using module/nomodule.

Idle until urgent

Idle until urgent is a code evaluation strategy conceived by Philip Walton from Google.

This strategy takes elements from the two most popular approaches to code evaluation – eager evaluation and lazy evaluation

Eager evaluation means all of your code is run right away. This approach results in a page that loads for a long time until it’s fully interactive but then runs smoothly without any hiccups.

Lazy evaluation is the opposite approach – your code is run only when it’s needed. While it has its benefits and might be useful for some websites, lazy evaluation means that once the code needs to be run, you risk having input delay.

Idle until urgent takes the best aspects of both approaches to provide a clever way to evaluate your code so that input delay is minimal.

Idle until urgent lets you run your code during idle periods, using the main thread to the fullest extent possible. At the same time, it guarantees that urgently needed code is run immediately. 

To get into the details of this code evaluation approach, read Philip Walton’s article and get familiar with the idle-until-urgent JavaScript library.

Taking the idle until urgent approach is a great way to improve your First Input Delay. Since code execution happens during idle periods only, you minimize the main thread blocking time.

 

Book15minCallIcon

Give us 15 minutes of your time and find out why big brands trust Onely with their major technical SEO issues.