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 的支持程度可能会有所差异,建议在目标浏览器上进行测试确认兼容性。

相关推荐
午安~婉4 小时前
Electron桌面应用聊天(续)
前端·javascript·electron
哟哟耶耶5 小时前
vue3-单文件组件css功能(:deep,:slotted,:global,useCssModule,v-bind)
前端·javascript·css
是罐装可乐5 小时前
深入理解“句柄(Handle)“:从浏览器安全到文件系统访问
前端·javascript·安全
华科易迅5 小时前
Vue如何集成封装Axios
前端·javascript·vue.js
不是az5 小时前
CSS知识点记录
前端·javascript·css
昵称暂无16 小时前
.NET 高级开发 | i18n 原理、实现一个 i18n 框架
javascript·c#·.net
h_jQuery6 小时前
vue使用gm-crypto对数据进行sm4加密处理
前端·javascript·vue.js
阿赛工作室7 小时前
Vue中onBeforeUnmount不触发的解决方案
前端·javascript·vue.js
浩星7 小时前
electron系列1:Electron不是玩具,为什么桌面应用需要它?
前端·javascript·electron
疯笔码良8 小时前
【Vue】自适应布局
javascript·vue.js·css3