Skip to content

INP: Interaction to Next Paint Optimization

最近在团队中落地INP 交互到下一帧绘制优化, and accumulated quite a bit of experience. Here's a summary for reference, hoping it helps those doing similar work.

Core Concepts

The key lies in understanding the core logic:

javascript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'largest-contentful-paint') {
      reportMetric('LCP', entry.startTime)
    }
    if (entry.entryType === 'first-input') {
      reportMetric('FID', entry.processingStart - entry.startTime)
    }
  }
})
observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input'] })

Performance optimization should be tailored to specific scenarios; not all cases require over-optimization.

In-Depth Analysis

We can improve it in the following ways:

javascript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'largest-contentful-paint') {
      reportMetric('LCP', entry.startTime)
    }
    if (entry.entryType === 'first-input') {
      reportMetric('FID', entry.processingStart - entry.startTime)
    }
  }
})
observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input'] })

This approach has been running stably in production for over six months and has been practically validated.

Implementation Experience

Let's start with the basic implementation:

javascript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'largest-contentful-paint') {
      reportMetric('LCP', entry.startTime)
    }
    if (entry.entryType === 'first-input') {
      reportMetric('FID', entry.processingStart - entry.startTime)
    }
  }
})
observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input'] })

This code demonstrates the basic usage. In real projects, you also need to consider error handling and edge cases.

Optimization Strategies

Building on this foundation, we can further optimize:

javascript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'largest-contentful-paint') {
      reportMetric('LCP', entry.startTime)
    }
    if (entry.entryType === 'first-input') {
      reportMetric('FID', entry.processingStart - entry.startTime)
    }
  }
})
observer.observe({ entryTypes: ['largest-contentful-paint', 'first-input'] })

This pattern is very practical in large projects and can significantly reduce maintenance costs.

Summary

  • INP 交互到下一帧绘制优化不是银弹,需要根据项目规模和技术栈选择
  • Understanding underlying principles is more important than memorizing APIs
  • Always verify compatibility before using in production
  • In team collaboration, conventions and documentation are more important than the technology itself

MIT Licensed