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

相关推荐
m0_471199634 小时前
【vue】通俗详解package-lock文件的作用
前端·javascript·vue.js
今天不要写bug4 小时前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
咬人喵喵5 小时前
14 类圣诞核心 SVG 交互方案拆解(附案例 + 资源)
开发语言·前端·javascript
韩曙亮6 小时前
【Web APIs】元素滚动 scroll 系列属性 ② ( 右侧固定侧边栏 )
前端·javascript·bom·window·web apis·pageyoffset
珑墨6 小时前
【浏览器】页面加载原理详解
前端·javascript·c++·node.js·edge浏览器
FreeBuf_6 小时前
Next.js 发布扫描工具:检测并修复受 React2Shell 漏洞(CVE-2025-66478)影响的应用
开发语言·javascript·ecmascript
馬致远6 小时前
Vue -组件入门
javascript·vue.js·ecmascript
御形封灵7 小时前
基于原生table实现单元格合并、增删
开发语言·javascript·ecmascript
Irene19917 小时前
Prettier 配置文件 .prettierrc.js 和 .prettierrc.json 的区别
javascript·json