Performance API 深度实战:Long Tasks、INP 与性能监控体系

性能优化(更新于 2026年6月20日)

Performance API 体系概览

浏览器 Performance API 提供了一套完整的性能度量与监控接口,从导航计时到元素渲染、从长任务检测到交互响应,覆盖了性能监控的全链路。

API 监控目标 类型
PerformanceObserver 各类性能条目的观察器 核心
PerformanceNavigationTiming 页面导航与加载 导航
PerformanceResourceTiming 资源加载耗时 资源
PerformanceLongTaskTiming 长任务(>50ms) 交互
PerformanceEventTiming 用户交互延迟 交互
PerformanceElementTiming 元素渲染时间 渲染
PerformanceLayoutShift 布局偏移 稳定性
PerformancePaintTiming 首次绘制/内容绘制 渲染

PerformanceObserver 基础

核心模式

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime, entry.duration);
  }
});

observer.observe({ type: 'longtask', buffered: true });

观察多个类型

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    switch (entry.entryType) {
      case 'longtask':
        reportLongTask(entry);
        break;
      case 'event':
        reportEventTiming(entry);
        break;
      case 'layout-shift':
        reportLayoutShift(entry);
        break;
      case 'element':
        reportElementTiming(entry);
        break;
    }
  }
});

observer.observe({
  type: ['longtask', 'event', 'layout-shift', 'element'],
  buffered: true
});

Long Tasks 监控

Long Tasks 是指主线程上执行超过 50ms 的任务,会阻塞用户交互并导致页面卡顿。

基础监控

const longTaskObserver = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log({
      name: entry.name,
      startTime: entry.startTime.toFixed(2),
      duration: entry.duration.toFixed(2),
      culprit: entry.attribution?.[0]?.containerType,
      containerName: entry.attribution?.[0]?.containerName,
    });
  }
});

longTaskObserver.observe({ type: 'longtask', buffered: true });

长任务归因分析

function analyzeLongTask(entry) {
  const attribution = entry.attribution?.[0];
  if (!attribution) return { type: 'unknown' };

  return {
    type: attribution.containerType,
    containerName: attribution.containerName,
    containerId: attribution.containerId,
    containerSrc: attribution.containerSrc,
    duration: entry.duration,
    startTime: entry.startTime,
  };
}

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    const analysis = analyzeLongTask(entry);
    reportToAnalytics('longtask', analysis);
  }
});

observer.observe({ type: 'longtask', buffered: true });

长任务优化策略

策略 说明 示例
任务拆分 将大任务拆分为 <50ms 的小任务 scheduler.yield()
延迟执行 非关键任务推迟到空闲期 requestIdleCallback
Web Worker CPU 密集型任务移至 Worker 数据处理、排序
代码分割 按需加载减少初始 JS 体积 动态 import()
调度优先级 使用 Scheduler API 控制执行顺序 scheduler.postTask
async function yieldToMain() {
  if ('scheduler' in window && 'yield' in scheduler) {
    return scheduler.yield();
  }
  return new Promise((resolve) => setTimeout(resolve, 0));
}

async function processLargeList(items) {
  const results = [];
  for (let i = 0; i < items.length; i++) {
    results.push(processItem(items[i]));
    if (i % 100 === 0) await yieldToMain();
  }
  return results;
}

Interaction to Next Paint (INP)

INP 是 Core Web Vitals 的交互响应指标,衡量用户与页面交互到下一次绘制的延迟。

INP 评分标准

评分 INP 值 用户体验
良好 ≤ 200ms 响应迅速
需改进 200-500ms 可感知延迟
较差 > 500ms 明显卡顿

监控 INP

let maxInteraction = 0;
let worstInteraction = null;

const inpObserver = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (!entry.interactionId) continue;

    const duration = entry.duration;
    if (duration > maxInteraction) {
      maxInteraction = duration;
      worstInteraction = {
        interactionId: entry.interactionId,
        type: entry.name,
        duration,
        startTime: entry.startTime,
        processingStart: entry.processingStart,
        processingEnd: entry.processingEnd,
        inputDelay: entry.processingStart - entry.startTime,
        processingDuration: entry.processingEnd - entry.processingStart,
        presentationDelay: entry.duration - (entry.processingEnd - entry.startTime),
      };
    }
  }
});

inpObserver.observe({ type: 'event', buffered: true, durationThreshold: 16 });

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    if (worstInteraction) {
      reportToAnalytics('inp', {
        value: maxInteraction,
        rating: maxInteraction <= 200 ? 'good' : maxInteraction <= 500 ? 'needs-improvement' : 'poor',
        ...worstInteraction,
      });
    }
  }
});

INP 延迟分解

用户交互 → 输入延迟 → 事件处理 → 呈现延迟 → 下一帧绘制
           ─────────────────────────────────────────────
           |←          INP (duration)                →|

输入延迟:startTime → processingStart
  原因:主线程被长任务阻塞

事件处理:processingStart → processingEnd
  原因:事件回调执行过慢

呈现延迟:processingEnd → 下一帧绘制
  原因:requestAnimationFrame 回调或样式/布局计算过重

Element Timing 监控

Element Timing 追踪关键内容的渲染时间,适用于 LCP 元素和自定义关键元素。

<img src="hero.jpg" elementtiming="hero-image" />
<p elementtiming="hero-text">关键内容</p>
<div elementtiming="main-content">...</div>
const elementObserver = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log({
      identifier: entry.identifier,
      startTime: entry.startTime,
      renderTime: entry.renderTime,
      loadTime: entry.loadTime,
      size: entry.size,
      url: entry.url,
      elementType: entry.element?.tagName,
    });
  }
});

elementObserver.observe({ type: 'element', buffered: true });

RUM 监控体系构建

核心指标收集器

class PerformanceMonitor {
  constructor(options = {}) {
    this.endpoint = options.endpoint;
    this.metrics = {};
    this.observers = [];
  }

  start() {
    this.collectWebVitals();
    this.collectLongTasks();
    this.collectResourceTiming();
    this.collectNavigationTiming();
    this.scheduleReport();
  }

  collectWebVitals() {
    this.observe('event', (entry) => {
      if (!entry.interactionId) return;
      this.metrics.inp = Math.max(this.metrics.inp ?? 0, entry.duration);
    });

    this.observe('largest-contentful-paint', (entry) => {
      this.metrics.lcp = entry.startTime;
    });

    this.observe('layout-shift', (entry) => {
      if (!entry.hadRecentInput) {
        this.metrics.cls = (this.metrics.cls ?? 0) + entry.value;
      }
    });

    this.observe('first-input', (entry) => {
      this.metrics.fid = entry.processingStart - entry.startTime;
    });
  }

  collectLongTasks() {
    this.observe('longtask', (entry) => {
      if (!this.metrics.longTasks) this.metrics.longTasks = [];
      this.metrics.longTasks.push({
        duration: entry.duration,
        startTime: entry.startTime,
        culprit: entry.attribution?.[0]?.containerType,
      });
    });
  }

  collectResourceTiming() {
    this.observe('resource', (entry) => {
      if (entry.duration > 1000) {
        if (!this.metrics.slowResources) this.metrics.slowResources = [];
        this.metrics.slowResources.push({
          name: entry.name,
          duration: entry.duration,
          initiatorType: entry.initiatorType,
          transferSize: entry.transferSize,
        });
      }
    });
  }

  collectNavigationTiming() {
    const [nav] = performance.getEntriesByType('navigation');
    if (nav) {
      this.metrics.ttfb = nav.responseStart - nav.requestStart;
      this.metrics.domContentLoaded = nav.domContentLoadedEventEnd - nav.startTime;
      this.metrics.loadComplete = nav.loadEventEnd - nav.startTime;
      this.metrics.domInteractive = nav.domInteractive - nav.startTime;
    }
  }

  observe(type, callback) {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) callback(entry);
    });
    observer.observe({ type, buffered: true });
    this.observers.push(observer);
  }

  scheduleReport() {
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'hidden') this.report();
    });
  }

  async report() {
    const payload = {
      url: location.href,
      timestamp: Date.now(),
      userAgent: navigator.userAgent,
      connection: navigator.connection
        ? { effectiveType: navigator.connection.effectiveType, downlink: navigator.connection.downlink }
        : null,
      metrics: this.metrics,
    };

    if (navigator.sendBeacon) {
      navigator.sendBeacon(this.endpoint, JSON.stringify(payload));
    } else {
      fetch(this.endpoint, { method: 'POST', body: JSON.stringify(payload), keepalive: true });
    }
  }

  destroy() {
    this.observers.forEach((o) => o.disconnect());
  }
}

const monitor = new PerformanceMonitor({ endpoint: '/api/vitals' });
monitor.start();

Core Web Vitals 指标全景

指标 全称 阈值(好/差) 监控类型 权重
LCP Largest Contentful Paint ≤2.5s / >4s largest-contentful-paint 25%
INP Interaction to Next Paint ≤200ms / >500ms event 25%
CLS Cumulative Layout Shift ≤0.1 / >0.25 layout-shift 25%
FCP First Contentful Paint ≤1.8s / >3s paint 10%
TTFB Time to First Byte ≤800ms / >1800ms navigation 15%

性能数据上报优化

批量上报与压缩

class MetricsBatcher {
  constructor(endpoint, options = {}) {
    this.endpoint = endpoint;
    this.batchSize = options.batchSize ?? 10;
    this.flushInterval = options.flushInterval ?? 5000;
    this.queue = [];
    this.timer = null;
  }

  enqueue(metric) {
    this.queue.push(metric);
    if (this.queue.length >= this.batchSize) this.flush();
    else if (!this.timer) {
      this.timer = setTimeout(() => this.flush(), this.flushInterval);
    }
  }

  flush() {
    if (this.timer) { clearTimeout(this.timer); this.timer = null; }
    if (this.queue.length === 0) return;

    const payload = JSON.stringify(this.queue);
    this.queue = [];

    if (navigator.sendBeacon) {
      navigator.sendBeacon(this.endpoint, payload);
    } else {
      fetch(this.endpoint, { method: 'POST', body: payload, keepalive: true });
    }
  }
}

最佳实践总结

  1. 使用 buffered: true:确保不遗漏页面加载早期的性能条目
  2. INP 在 visibilitychange 时上报:取会话内最差交互值
  3. 长任务归因:利用 attribution 定位问题来源(iframe/script)
  4. sendBeacon 优先:页面卸载时保证数据送达
  5. 关注 INP 三段延迟:分别优化输入延迟、事件处理、呈现延迟

本站提供浏览器本地工具,免注册即可试用 →

#Performance API#PerformanceObserver#Long Tasks#INP#性能监控