javascript的performance api是什么_如何测量性能?

admin 百科 14
Performance API 是浏览器原生高性能监控工具,支持微秒级精度测量代码执行、页面生命周期、资源加载、渲染指标及长任务,无需第三方库。

javascript的performance api是什么_如何测量性能?-第1张图片-佛山资讯网

Performance API 是浏览器提供的一套原生接口,用来精确获取页面运行时的性能数据,比如加载时间、渲染帧率、资源加载耗时、内存使用、长任务等。它不依赖第三方库,精度高(微秒级),是前端性能监控和优化的核心工具。

常用 Performance 方法和场景

最常用的是 performance.now()performance.mark() 配合 performance.measure(),适合测量任意代码段执行耗时:

  • performance.now() 返回当前时刻的高精度时间戳(单位:毫秒,精度可达微秒),比 Date.now() 更准,且不受系统时间调整影响
  • performance.mark('start') 打标记,performance.mark('end') 再打一个,然后用 performance.measure('myTask', 'start', 'end') 计算两者间隔
  • 测量结果可通过 performance.getEntriesByName('myTask') 获取,返回包含 duration 的对象

获取页面整体生命周期关键时间点

performance.timing(已废弃但仍有兼容)和更现代的 performance.getEntriesByType('navigation') 可拿到导航相关的完整时间线:

  • 例如 navigationStart(导航开始)、domContentLoadedEventEnd(DOM 加载完成)、loadEventEnd(页面完全加载)等
  • 推荐用 performance.getEntriesByType('navigation')[0] 读取,字段名一致但语义更清晰,且支持多页导航记录
  • 注意:这些时间基于 performance.timeOrigin,不是绝对时间,而是相对页面创建时刻的偏移量

监控资源加载与渲染表现

performance.getEntriesByType('resource') 查看每个脚本、样式、图片等的加载耗时;用 performance.getEntriesByType('paint') 获取首次绘制(first-paint)和首次内容绘制(first-contentful-paint)时间:

标签: javascript java js 前端 浏览器 edge 工具 ssl ai dns

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~