Web Performance API 深度实践:Navigation/Resource Timing、PerformanceObserver 与指标采集技术背景Web Performance API 为前端提供详尽的时序与资源性能数据。通过 Navigation/Resource Timing 与 PerformanceObserver 实时采集,结合核心指标(FCP/LCP/CLS/FID/TTFB),可构建数据驱动的优化体系。核心内容导航与首包时序采集function getNavigationTimings() {

const [nav] = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[];

if (!nav) return null;

return {

ttfb: nav.responseStart - nav.requestStart,

domContentLoaded: nav.domContentLoadedEventEnd - nav.startTime,

loadEvent: nav.loadEventEnd - nav.startTime,

redirect: nav.redirectEnd - nav.redirectStart,

dns: nav.domainLookupEnd - nav.domainLookupStart,

tcp: nav.connectEnd - nav.connectStart,

tls: nav.secureConnectionStart ? nav.connectEnd - nav.secureConnectionStart : 0

};

}

资源加载时序与慢资源识别function observeResources(threshold = 3000) {

if (!('PerformanceObserver' in window)) return;

const po = new PerformanceObserver((list) => {

for (const e of list.getEntries()) {

if (e.entryType === 'resource') {

const time = e.responseEnd - e.startTime;

if (time > threshold) {

console.warn('Slow resource', e.name, time);

navigator.sendBeacon('/rum/resource', JSON.stringify({ name: e.name, time, ts: Date.now() }));

}

}

}

});

po.observe({ entryTypes: ['resource'] });

}

核心指标监听(FCP/LCP/CLS/FID)function observeCoreWebVitals() {

const metrics: Record<string, number> = {};

// Paint(FCP)

const paintObs = new PerformanceObserver((list) => {

for (const e of list.getEntries()) {

if (e.name === 'first-contentful-paint') metrics.fcp = e.startTime;

}

});

paintObs.observe({ type: 'paint', buffered: true } as any);

// LCP

const lcpObs = new PerformanceObserver((list) => {

for (const e of list.getEntries()) metrics.lcp = (e as any).startTime;

});

lcpObs.observe({ type: 'largest-contentful-paint', buffered: true } as any);

// FID

const fidObs = new PerformanceObserver((list) => {

for (const e of list.getEntries()) {

const entry = e as any;

metrics.fid = entry.processingStart - entry.startTime;

}

});

fidObs.observe({ type: 'first-input', buffered: true } as any);

// CLS

let cls = 0;

const clsObs = new PerformanceObserver((list) => {

for (const e of list.getEntries()) {

const entry = e as any;

if (!entry.hadRecentInput) cls += entry.value;

metrics.cls = cls;

}

});

clsObs.observe({ type: 'layout-shift', buffered: true } as any);

// 汇报

window.addEventListener('load', () => {

navigator.sendBeacon('/rum/vitals', JSON.stringify({ ...metrics, ts: Date.now(), url: location.href }));

});

}

技术验证参数在 Chrome 128/Edge 130(Windows 11,企业应用与电商站点)真实流量:指标采集成功率:≥ 97%慢资源识别准确率(>3s):≥ 95%指标目标:FCP < 1.8s,LCP < 2.5s,FID < 100ms,CLS < 0.1,TTFB < 300ms应用场景数据驱动的性能优化与回归检测慢接口与静态资源定位与治理A/B 实验与边缘/缓存策略效果评估最佳实践采用 `buffered: true` 捕获早期指标,避免遗漏对资源条目做白名单与敏感路径标记,精准分析与告警/看板对接形成闭环,持续优化迭代

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部