常用性能测量APIs(关键时间节点、观察长任务、网络状态)

155 阅读2分钟

「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。

Web标准APIs

1. 关键时间节点(Navigation Timing, Resource Timing)

1.1 重要的时间节点计算公式

  • DNS 解析耗时: domainLookupEnd - domainLookupStart
  • TCP 连接耗时: connectEnd - connectStart
  • SSL 安全连接耗时: connectEnd - secureConnectionStart
  • 网络请求耗时 (TTFB): responseStart - requestStart
  • 数据传输耗时: responseEnd - responseStart
  • DOM 解析耗时: domInteractive - responseEnd
  • 资源加载耗时: loadEventStart - domContentLoadedEventEnd
  • First Byte时间: responseStart - domainLookupStart
  • 白屏时间: responseEnd - fetchStart
  • 首次可交互时间: domInteractive - fetchStart
  • DOM Ready 时间: domContentLoadEventEnd - fetchStart
  • 页面完全加载时间: loadEventStart - fetchStart
  • http 头部大小: transferSize - encodedBodySize
  • 重定向次数:performance.navigation.redirectCount
  • 重定向耗时: redirectEnd - redirectStart

1.2 计算首次可交互时间的性能指标 :示例

// 计算首次可交互时间的性能指标
window.addEventListener('load', (event) => {
    // Time to Interactive
    let timing = performance.getEntriesByType('navigation')[0];
    console.log(timing.domInteractive);
    console.log(timing.fetchStart);
    
    let diff = timing.domInteractive - timing.fetchStart;
    console.log("TTI: " + diff);
})

1.3 作用

简单来说,可以让我们真实的知道

  • 网站打开速度快不快,
  • 页面中的动画够不够流畅
  • 表单提交的速度是否够快
  • 列表滚动页面切换是否卡顿
  • ... 等等性能,而不是通过本地的一些模拟来呈现出来

我们把这些数据上报后,可以对数据进一步分析,进行更有 针对性 的性能优化,

woman-reads-through-meeting-info.jpg

2. 观察长任务 PerformanceObserver

例如我们有下面这样的一个长任务

const start = new Date().getTime();
const calculatePi = (duration)=> {
    while (new Date().getTime() < start + duration) {
        // TODO(Dereck): figure out the Math problem
    }
}
calculatePi(1000 * 20)

我们可以这样的进行监听

// 观察长任务
const observers = new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
        console.log(entry)
    }
})

observers.observe({entryTypes: ['longtask']})

3. 页面可见性的状态监听

可以用于:

  1. 音视频分播放: 用户离开当前页面(tab切换),暂停播放,节流
  2. 游戏:暂停游戏或者存档,等回来再进行恢复
// 见面可见性的状态监听
let vEvent = 'visibilitychange';
if (document.webkitHidden != undefined) {
    // webkit prefix detected
    vEvent = 'webkitvisibilitychange';
}

function visibilityChanged() {
    if (document.hidden || document.webkitHidden) {
        console.log("Web page is hidden.")
    } else {
        console.log("Web page is visible.")
    }
}

document.addEventListener(vEvent, visibilityChanged, false);

4. 获取浏览器当前网络状态

根据网络状态来使用不同大小尺寸的图片

很多图片的CDN提供商,都是支持在不同质量、尺寸、格式的图片

例如:七牛API 文档# 图片基本处理(imageView2) image.png

使用 navigator.connection || navigator.mozConnection || navigator.webkitConnection来获取当前的网速

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
  console.log("Connection type changed from " + type + " to " + connection.effectiveType);
  type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);