构建自定义PerformanceEntry需在标准API内用mark/measurement打点并配合PerformanceObserver上报,确保语义明确、时序正确、兼容降级且上报聚合可追溯。
要构建符合业务需求的自定义 PerformanceEntry,关键不在于“造轮子”,而是在标准 Performance API 框架内精准打点、合理归类、稳定上报。浏览器原生不支持直接创建任意 PerformanceEntry 实例(如 new PerformanceEntry() 会报错),但可通过 performance.mark() 和 performance.measure() 配合 PerformanceObserver 实现等效效果,并赋予业务语义。
所有自定义性能指标都应基于用户可感知的关键路径,比如「商品详情页首屏渲染完成」「搜索结果列表加载耗时」「支付按钮点击到弹窗出现」。这类指标无法被 LCP、FCP 等通用指标覆盖,需手动标记:
performance.mark('product-detail-first-paint'),名称需唯一且语义明确performance.mark('product-detail-ready')
performance.measure('product-detail-ssr-to-client', 'product-detail-first-paint', 'product-detail-ready'),生成一条 type="measure" 的 entryperformance.getEntriesByType('measure') 结果中,name 为 measure 名,duration 为毫秒值,startTime 为起始 mark 时间偏移仅生成 entry 不够,还需注入业务维度信息(如页面类型、用户等级、AB 实验分组),这需在 observer 回调中完成:
{ entryTypes: ['measure'] },否则回调永不触发entryList.getEntries(),筛选出你关心的 measure namepageType: 'product'、abGroup: 'v2'、isLogin: true,存入自定义上报 payload真实环境中,自定义打点极易因环境或误用失效,需主动防御:
if (performance.getEntriesByName('xxx').length === 0) performance.mark('xxx')
getEntriesByType,需降级为定时轮询 performance.getEntries() 并按 entryType 过滤自定义指标的价值体现在分析端,上报结构需兼顾灵活性与可查询性:
name(业务标识)、duration(核心数值)、timestamp(performance.timeOrigin + entry.startTime)、navigationType(来自 performance.navigation.type)、pagePath(当前 URL 或路由 path)traceId 字段,关联同一次用户操作下的多个指标(如从点击到接口响应再到渲染),便于下钻分析navigator.sendBeacon() 上报,确保页面卸载前也能发出;若不可用,降级为 fetch + keepalive