登录
首页 >  文章 >  前端

PerformanceAPI优化JavaScript性能技巧

时间:2025-12-14 20:55:43 306浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

怎么入门文章编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Performance API如何提升JavaScript性能》,涉及到,有需要的可以收藏一下

Performance API通过高精度时间戳提供页面加载、资源请求等性能数据。1. 使用performance.now()获取精确时间;2. 用mark和measure测量自定义逻辑耗时;3. 通过navigation条目计算DNS、TCP、白屏等关键指标;4. 利用PerformanceObserver监听动态资源加载。结合上报机制可构建完整前端监控体系,持续优化用户体验。

JavaScript性能监控_PerformanceAPI

前端性能监控是优化用户体验的关键环节,JavaScript中的Performance API为开发者提供了精确测量应用性能的能力。它基于高精度时间戳,能帮助我们获取页面加载、资源请求、脚本执行等关键阶段的耗时信息。

Performance API 核心功能

Performance API 是浏览器内置的接口,位于 window.performance 对象下,主要包含以下几个核心部分:

  • performance.now():返回自页面加载以来的高精度时间(毫秒),比 Date.now() 更精确,不受系统时钟调整影响。
  • performance.timing:提供页面加载各个阶段的时间戳(已废弃,推荐使用 Navigation Timing Level 2)。
  • performance.getEntries():获取所有已记录的性能条目,包括资源加载、Paint、Frame 等。
  • performance.mark()performance.measure():用于自定义打点和测量时间段。

使用 mark 和 measure 进行自定义性能测量

在复杂应用中,我们常需要测量某段逻辑的执行时间,比如接口响应、组件渲染等。利用 mark 和 measure 可轻松实现:

// 打标记
performance.mark('start-data-fetch');
<p>fetch('/api/data')
.then(res => res.json())
.then(data => {
performance.mark('end-data-fetch');
// 记录耗时
performance.measure('data-fetch-time', 'start-data-fetch', 'end-data-fetch');
});</p>

之后可通过 performance.getEntriesByType('measure') 获取测量结果:

const measures = performance.getEntriesByType('measure');
console.log(measures); // [{ name: "data-fetch-time", duration: 120.5, ... }]

监控页面加载性能

利用 navigationStartloadEventEnd 等时间点,可以计算关键性能指标:

const perfData = performance.getEntriesByType("navigation")[0];
console.log(`DNS查询耗时: ${perfData.domainLookupEnd - perfData.domainLookupStart}`);
console.log(`TCP连接耗时: ${perfData.connectEnd - perfData.connectStart}`);
console.log(`白屏时间: ${perfData.responseStart - perfData.navigationStart}`);
console.log(`DOM渲染完成: ${perfData.domContentLoadedEventEnd - perfData.navigationStart}`);
console.log(`页面完全加载: ${perfData.loadEventEnd - perfData.navigationStart}`);

结合 PerformanceObserver 监听动态资源

对于异步加载的资源(如图片、脚本),可使用 PerformanceObserver 实时监听:

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`${entry.name} 加载耗时: ${entry.duration}`);
    // 可上报到服务器
  }
});
// 观察资源加载
observer.observe({ entryTypes: ['resource'] });

这种方式适用于懒加载图片、动态 import 等场景,能更全面地掌握运行时性能表现。

基本上就这些。Performance API 提供了从页面加载到运行时测量的完整能力,合理使用可以帮助我们定位瓶颈、优化体验,并建立可持续的前端监控体系。不复杂但容易忽略细节,建议结合上报机制长期跟踪。

今天关于《PerformanceAPI优化JavaScript性能技巧》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>