概览INP 衡量用户输入到页面响应的整体延迟。通过 `PerformanceObserver` 采集 `event` 条目可定位交互瓶颈,并以任务切分、渲染稳定与资源调度方式降低延迟。采集与上报'use client' let maxEvent = 0 const po = new PerformanceObserver((list) => { for (const e of list.getEntries() as PerformanceEventTiming[]) { if (e.name === 'click' || e.name === 'pointerdown' || e.name === 'keydown') { maxEvent = Math.max(maxEvent, e.duration) } } }) po.observe({ type: 'event', buffered: true, durationThreshold: 16 }) addEventListener('beforeunload', () => { navigator.sendBeacon('/api/vitals', JSON.stringify({ inp: maxEvent })) }) 任务切分与让渡function handleClick() { // 轻任务立即响应 updateUI() // 重任务让渡主线程 setTimeout(() => heavyCompute(), 0) } function heavyCompute() { // 将长任务拆分为片段 const chunk = 1000 for (let i = 0; i < 50000; i += chunk) { // 片段处理... } } 样式与布局稳定/* 关键图片与组件设置尺寸,避免过度重排 */ img { width: 100%; height: auto; } /* 使用 clamp/sizes 减少字体与图片引起的抖动 */ 治理要点避免同步阻塞(JSON 解析、复杂排序)占用输入响应路径。对网络请求使用缓存与退避策略,减少交互等待。结合 Worker 将重计算移出主线程。验证与指标浏览器:Chrome 120+、Edge 120+、Safari/Firefox 支持逐步完善(退化为体验优化指导)INP:降至 200ms 以下;交互响应可靠、无明显卡顿

发表评论 取消回复