Performance 计算白屏和首屏时间

什么是白屏和首屏时间

白屏时间(FP)

白屏时间(First Paint):是指浏览器从响应用户输入网址地址,到浏览器开始显示内容的时间。

  • 白屏时间 = 页面开始展示的时间点 - 开始请求的时间点

首屏时间(FCP)

首屏时间(First Contentful Paint):是指浏览器从响应用户输入网络地址,到首屏内容渲染完成的时间。

  • 首屏时间 = 首屏内容渲染结束时间点 - 开始请求的时间点

performance计算白屏和首屏时间

performance包含三个对象,分别为 memory、navigation、timing

详细属性,参照developer.mozilla.org/zh-CN/docs/...

performance 来实现我们经常关注的一些指标的计算和上报:

ini 复制代码
重定向耗时 = redirectEnd - redirectStart;

DNS查询耗时 = domainLookupEnd - domainLookupStart;

TCP链接耗时 = connectEnd - connectStart;

HTTP请求耗时 = responseEnd - responseStart;

解析dom树耗时 = domComplete - domInteractive;

白屏时间 = responseStart - navigationStart; 

DOMready时间/首屏渲染时间 = domContentLoadedEventEnd - navigationStart;

onload时间 = loadEventEnd - navigationStart;

注:

  • 白屏时间:whiteScreenTime = performance.timing.responseStart - performance.timing.navigationStart
  • 首屏渲染时间: firstScreenTime = performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart

PerformanceObserver计算白屏和首屏时间

随着 performance.timing API 的逐渐废除,我们可以使用新的 PerformanceObserver API 来监听页面加载的性能指标,包括白屏时间和首屏渲染时长。

下面是一个简单的示例代码,展示了如何使用 PerformanceObserver 监听白屏时间和首屏渲染时长:

js 复制代码
// 创建 PerformanceObserver 实例
const observer = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach(entry => {
    if (entry.entryType === 'paint') {
      if (entry.name === 'first-contentful-paint') {
        console.log('首次内容绘制时间(First Contentful Paint):', entry.startTime);
      } else if (entry.name === 'first-paint') {
        console.log('白屏时间(First Paint):', entry.startTime);
      }
    }
  });
});

// 开始监听页面性能
observer.observe({ entryTypes: ['paint'] });

**

在上述代码中,我们创建了一个 PerformanceObserver 实例,并通过 observe 方法指定了要监听的 entryTypes 为 'paint',表示我们要监听页面绘制的性能指标。在回调函数中,我们通过遍历获取到的性能条目来识别首次内容绘制时间(First Contentful Paint)和白屏时间(First Paint)。

通过这种方式,我们可以使用 PerformanceObserver API 来监听页面加载过程中的关键性能指标,包括白屏时间和首屏渲染时长,帮助我们更好地优化页面加载性能。需要注意的是,不同浏览器对于 PerformanceObserver 的支持程度可能会有所差异,建议在目标浏览器上进行测试确认兼容性。

相关推荐
前端小巷子7 分钟前
跨域问题解决方案:开发代理
前端·javascript·面试
JohnYan7 分钟前
Bun技术评估 - 07 S3
javascript·后端·bun
Mintopia7 分钟前
Three.js 材质与灯光:一场像素级的光影华尔兹
前端·javascript·three.js
天涯学馆9 分钟前
JavaScript 跨域、事件循环、性能优化面试题解析教程
前端·javascript·面试
江城开朗的豌豆25 分钟前
路由守卫通关秘籍:这些钩子函数让你的页面跳转稳如老狗!
前端·javascript·vue.js
sunbyte34 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | DragNDrop(拖拽占用组件)
前端·javascript·css·vue.js·vue
柚子81637 分钟前
告别FLIP动画:View Transition API带来的革命性变革
前端·javascript
天涯学馆41 分钟前
JS 组合模式在组件化开发中的应用:从原理到实战
前端·javascript·面试
FogLetter42 分钟前
闭包:JavaScript中的魔法背包
前端·javascript
江城开朗的豌豆43 分钟前
Vuex中mutations和actions的那些事儿:为啥非要分家?
前端·javascript·vue.js