performance.mark()和performance.measure()可原生精准打点测时;mark用语义化字符串标记关键节点,measure计算两mark间耗时并存入timeline;需手动getentries获取、过滤后上报。

用 Performance.mark() 和 Performance.measure() 可以在 JS 中轻量、精准地打点并计算任意两段逻辑之间的耗时,无需第三方库,原生支持,兼容性好(Chrome 25+、Firefox 41+、Edge 12+、Safari 11+)。
怎么打自定义时间标记(mark)
performance.mark(name) 在性能时间轴上记录一个带名字的高精度时间戳。它不自动关联任何上下文,纯靠名字标识,所以命名要有语义、可区分。
- 名字必须是字符串,不能重复(重复会报错:DOMException)
- 适合标记关键节点:比如“接口开始请求”“模板编译完成”“首屏渲染结束”
- 示例:
performance.mark('api-fetch-start');performance.mark('render-first-screen-end');
怎么测量两个 mark 之间的时间差(measure)
performance.measure(name, startMark, endMark) 会计算从 startMark 到 endMark 的耗时(单位毫秒),并把结果存入 performance timeline。
-
startMark和endMark必须是已存在的 mark 名字(顺序不能反) - 生成的 measure 对象可通过
performance.getEntriesByName(name, 'measure')获取 - 示例:
performance.measure('api-fetch-duration', 'api-fetch-start', 'api-fetch-end');performance.measure('first-screen-paint', 'route-enter', 'render-first-screen-end');
怎么获取和上报测量结果
measure 不会自动上报,需手动提取并发送到监控服务:
- 用
performance.getEntriesByType('measure')拿到所有 measure 记录 - 或按名精确获取:
performance.getEntriesByName('api-fetch-duration', 'measure') - 每条 entry 包含
name、startTime、duration(核心字段)、entryType等 - 建议过滤掉 duration ≤ 0 的异常项,再通过
fetch或Image打点上报 - 示例:
const entries = performance.getEntriesByName('first-screen-paint', 'measure');if (entries.length) {
sendToMonitor({
type: 'fs-paint',
duration: Math.round(entries[0].duration),
timestamp: Date.now()
});}
注意事项和实用技巧
避免踩坑,让埋点真正可用:
- 不要在同一名字下多次调用
mark,如需覆盖,先用performance.clearMarks(name) - measure 依赖 mark 存在,确保
endMark一定在startMark之后执行(异步场景注意时序) - 页面卸载前(如
beforeunload)可集中收集未上报的 measure 并快速发送(注意浏览器可能截断) - 开发期可用
performance.getEntries()在控制台实时查看所有 mark/measure - 搭配
performance.clearMarks()和performance.clearMeasures()避免内存堆积(尤其 SPA 多次路由)
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











