Optimize Interaction to Next Paint (INP) for Better Web Performance

Google’s web performance metrics are constantly evolving to provide developers with better insights into how their websites are performing. One of the latest additions to these metrics is Interaction to Next Paint (INP). This article will provide an in-depth look at what INP is, why it’s essential, and how you can optimize it to improve your website’s performance and user experience.

Table of Contents

What is Interaction to Next Paint (INP)?

Interaction to Next Paint (INP) is a web performance metric that measures user interface responsiveness. Specifically, it measures the time that elapses between a user interaction, such as a click or key press, and the next visual update on the page. This metric is crucial as it directly impacts the user’s perception of your website’s responsiveness.

INP is composed of three components:

  1. Input Delay: The time taken for background tasks on the page that prevent the event handler from running.
  2. Processing Time: The time taken to run event handlers in JavaScript.
  3. Presentation Delay: The time taken to recalculate the page layout and paint the page content.

A good INP value is less than 200 milliseconds, while an INP over 500 milliseconds is considered poor. Starting from March 2024, INP will become one of the Core Web Vitals metrics that impact Google rankings.

Why is INP Important?

INP is important because it directly impacts the user’s experience on your website. A high INP value means that users have to wait longer to see a response to their interactions, which can lead to frustration and potentially cause users to leave your site. By optimizing INP, you can ensure that your website feels responsive and provides a smooth user experience.

How to Optimize INP

Optimizing INP primarily involves reducing the amount of CPU processing that happens on your page. Here are some strategies to achieve this:

Reduce Input Delay

To reduce the Input Delay component of INP, you need to minimize and break up background CPU activity on the main thread. If third-party code is responsible for background tasks, check if the code is configurable to reduce the amount of work or if it’s possible to only load the third-party script when necessary.

Reduce Processing Time

Optimizing the Processing Time component involves investigating where the browser is spending most of its time and optimizing those parts. For instance, in a React app, you might be able to avoid unnecessary rerenders of your components to speed up your website. If a lot of CPU activity consists of layout work, check if you can reduce relayouts.

Reduce Presentation Delay

The amount of Presentation Delay depends on the complexity of the page and how much of the page is updating. If rendering the page contents is slow, consider only showing important “above the fold” content first to deliver the next frame more quickly.

Measuring Interaction to Next Paint (INP)

Understanding how to measure INP is crucial for optimizing it. The goal of measuring INP is to understand how fast your page responds to user input. The only way to get realistic data is to measure how your page is responding to real users visiting your site using data from the field. Lab tools can then be used to better understand event timings and where optimizations need to happen.

Field Data

Field data is collected from real users interacting with your website. This data can provide a realistic picture of your website’s performance as it includes the variability of network conditions, device capabilities, and user behavior.

PageSpeed Insights

PageSpeed Insights is a tool provided by Google that pulls field data from the Chrome User Experience (CrUX) Report API, and gives a snapshot of your page and origin’s performance over the previous 28 days. This data now includes INP.

PageSpeed Insights Core Vitals

You can try it out at PageSpeed Insights.

Web Vitals Library

The web-vitals library is a JavaScript library developed by Google to measure Core Web Vitals. The library now has full INP support in its beta release. You can use it to collect INP data for your site.

Here’s an example of how to use the web-vitals library to measure INP:

import {onINP} from 'web-vitals';

onINP(({value}) => {
  // Log the value to the console, or send it to your analytics provider.
  console.log(value);
});

Web Vitals Chrome extension

The Web Vitals extension provides a dual perspective on your users’ page experience by offering a summary from the CrUX API and real-time data on Core Web Vitals and other crucial metrics during a user’s active session on the page.

Web Vitals Chrome extension

You can install the Web Vitals extension for Chrome from the web store.

Lab Data

Lab data is collected in a controlled environment and can help you understand where you need to optimize. Lab tools won’t automatically interact with the page, so they either need manual input while they measure, or they need to be scripted with an automation tool like Puppeteer.

Lighthouse User Flows

The new timespan mode in the Lighthouse Panel in DevTools lets you start Lighthouse, interact with your test page however you wish, and then get a report of what happened during that time. This report now includes INP and an audit to help diagnose any responsiveness issues.

The same series of interactions can be automated by using Lighthouse user flows. INP is available in user flows as of Lighthouse 9.6.

Real-World Examples of INP Optimization

Let’s look at some real-world examples of how you can optimize INP:

Using Web Workers for Heavy Computations

Web Workers allow you to run JavaScript in background threads, offloading heavy computations that would otherwise block the main thread and increase INP.

// main.js
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
  console.log('Received result from worker:', event.data);
};

// Send a heavy computation to the worker
worker.postMessage({ type: 'COMPUTE', payload: { /* ... */ } });

// worker.js
self.onmessage = function(event) {
  if (event.data.type === 'COMPUTE') {
    const result = heavyComputation(event.data.payload);
    self.postMessage(result);
  }
};

function heavyComputation(payload) {
  // Perform heavy computation here...
}

Using requestIdleCallback for Non-Essential Processing

requestIdleCallback allows you to schedule work when there is free time at the end of a frame, or when the user is inactive. This can be a good place to put non-essential work that doesn’t need to happen immediately after user interaction.

button.addEventListener('click', () => {
  // Immediate UI update
  button.textContent = 'Processing...';

  // Non-essential processing
  window.requestIdleCallback(() => {
    // Perform non-essential processing here...
    button.textContent = 'Done!';
  });
});

Avoiding Layout Thrashing

Layout thrashing occurs when you repeatedly read and write to the DOM, causing the browser to recalculate the layout multiple times. This can be avoided by batching your reads and writes.

// Bad example
elements.forEach(element => {
  const height = element.offsetHeight; // read
  element.style.height = height + 'px'; // write
});

// Good example
const heights = elements.map(element => element.offsetHeight); // batched read
elements.forEach((element, index) => {
  element.style.height = heights[index] + 'px'; // batched write
});

Provide immediate feedback to the user

Let the user know immediately that something is going to happen, and do the heavy work after that.

// POOR
// ---------------------------------------------------
const poor = document.getElementById('poor');

poor.addEventListener('click', () => {
  const st = new Date();
  
  // Heavy CPU task
  for (let i = 0; i < 300000; i++) {
    console.log(i);
  }
  
  // UI update
  const inpScore = (new Date() - st);
  poor.textContent = `Clicked! Poor INP score: ${inpScore}ms`;
});


// GOOD
// ---------------------------------------------------
const good = document.getElementById('good');

good.addEventListener('click', () => {
  const st = new Date();
  
  // UI update
  const inpScore = (new Date() - st);
  good.textContent = `Processing... Good INP: ${inpScore}ms`;

  // Heavy CPU task
  setTimeout(() => {
    for (let i = 0; i < 300000; i++) {
      console.log(i);
    }
    // Final UI update
    good.textContent = `Done! Good Final INP: ${inpScore}ms`;
  }, 0);
});

Live example

Here’s a live example on Codepen that may help you to better understand INP:

See the Pen Untitled by Andrei Surdu (@Andrei-Surdu) on CodePen.

FAQ: Interaction to Next Paint (INP) in WordPress

What is Interaction to Next Paint (INP)?

INP is a web performance metric that measures the time it takes for the first visual change to occur on the screen after a user interacts with your website, such as clicking a button or typing in a form. Lower INP indicates a more responsive and user-friendly experience.

Why is INP important for WordPress websites?

A slow INP can lead to a frustrating user experience, making users perceive your website as slow and unresponsive. This can negatively impact user engagement, conversion rates, and overall SEO performance.

How can I measure INP on my WordPress website?

While there isn’t a built-in WordPress tool for INP, you can use various tools like Google Chrome DevTools or Lighthouse to measure it. These tools provide detailed performance reports, including INP values.

What are some ways to optimize INP on my WordPress website?

The blog post outlines several strategies, including:
Minimizing JavaScript: Reduce the amount of JavaScript code on your website, as it can significantly impact rendering speed.
Deferring non-critical scripts: Defer loading of scripts that aren’t crucial for initial page load until after the initial content is rendered.
Optimizing images: Ensure your images are properly sized and compressed to minimize their loading time.
Using a Content Delivery Network (CDN): A CDN can deliver static content like images and scripts from geographically distributed servers, improving loading times for users in different locations.

Are there any plugins that can help me optimize INP?

While there aren’t any plugins specifically dedicated to INP, some performance optimization plugins can indirectly improve INP by addressing factors like JavaScript management and image optimization.

I’m not comfortable making code changes. Are there other options?

If you’re not comfortable with code, consider working with a WordPress developer or using a managed WordPress hosting provider that often offers performance optimization services.

Conclusion

By understanding and optimizing INP, you can significantly improve your website’s performance and user experience. Remember, the specific optimizations that will be most effective for you depend on your specific application and its performance profile, but the goal is to keep INP as low as possible to ensure a responsive and smooth user experience. Happy optimizing!

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *