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

相关推荐
跟着珅聪学java4 小时前
js编写中文转unicode 教程
前端·javascript·数据库
英俊潇洒美少年4 小时前
Vue3 深入响应式系统
前端·javascript·vue.js
颜酱4 小时前
回溯算法实战练习(3)
javascript·后端·算法
我命由我123456 小时前
React Router 6 - 概述、基础路由、重定向、NavLink、路由表
前端·javascript·react.js·前端框架·ecmascript·html5·js
yaaakaaang6 小时前
(四)前端,如此简单!---Promise
前端·javascript
aini_lovee6 小时前
C# 实现邮件发送源码(支持附件)
开发语言·javascript·c#
英俊潇洒美少年7 小时前
js 进程与线程的讲解
javascript
汉堡大王95279 小时前
# AI 终于能"干活"了——Function Calling 完全指南
javascript·人工智能·机器学习
吴声子夜歌9 小时前
JavaScript——call()、apply()和bind()
开发语言·前端·javascript
小哈猪9 小时前
CSS Flex 与 Grid:谁才是布局之王?
javascript