Getting started in window.performance

如何理解 window.performance

window.performance 是由 W3C 性能小组提出的用于精确计算网页性能数据的特性,它返一个 Performance 对象,支持 IE9 以上的全部浏览器,这里给出对象的原型:浏览器

clipboard.png

Performance.timing服务器

返回 PerformanceTiming 对象,包含延迟相关的性能信息。网络

Performance.navigation函数

返回 PerformanceNavigation 对象,该对象表示在当前给定浏览上下文中网页导航的类型(TYPE_BACK_FORWARD,TYPE_NAVIGATE,TYPE_RELOAD,TYPE_RESERVED)以及次数。工具

performance.memory性能

在 Chrome 中添加的一个非标准扩展,返回内存占用的基本信息。(尽可能避免使用非标准化API)测试

Performance.timeOriginspa

返回关于性能评估的开始时间(高分辨率时间戳)code

clipboard.png

Performance.onresourcetimingbufferfull orm

当 resourcetimingbufferfull 事件触发时,做为事件处理回调

function buffer_full_handler(event) {
    console.log('[Warning]: Resource Timing Buffer is full');
    performance.setResourceTimingBufferSize(200); // size >= 150
}

function initPerformanceMeasurement() {
    if (performance === undefined) {
        console.log("[Warning]: Performance interface is not supported");
        return
    }
    // Set a callback if the resource buffer becomes filled
    performance.onresourcetimingbufferfull = buffer_full_handler;
}

document.body.onload = initPerformanceMeasurement;

一般建议 performance entry 应该知足至少 150 个以上

为什么使用 Performance

一般熟悉 Chrome 开发者工具的朋友都会在开发环境下用到网络面板的相关操做,当咱们开启记录功能时,就会实时传回关于网页响应阶段的性能数据,但当咱们须要统计分析用户打开网页时的性能,所以咱们将 performance 原始信息或经过简单计算后的信息上传到服务器,配合其余网络属性(例如 HTTP 请求头信息),就能够很好地进行性能上报。

项目中的应用

1.判断是否刷新页面

const performance = window.performance

if(performance.navigation.type === 1) {
    console.log('Page was not reloaded.')
} else {
    console.log('Page was reloaded.')
}

这里的 performance.navigation.type 返回一个整数值,表示网页的加载来源,有如下几种状况:

返回值:0
类型常量:performance.navigation.TYPE_NAVIGATENEXT
描述:网页经过点击连接地址栏输入表单提交脚本操做等方式加载

返回值:1
类型常量:performance.navigation.TYPE_RELOAD
描述:网页经过 刷新 按钮或者 location.reload() 方法加载

返回值:2
类型常量:performance.navigation.TYPE_BACK_FORWARD
描述;网页经过 前进后退 按钮加载

返回值:255
类型常量:performance.navigation.TYPE_UNDEFINED
描述:网页经过其它 任何可执行的来源 加载

此外,经过 performance.navigation.redirectCount 能够获取当前网页重定向跳转的次数

2.测试函数执行时间

function fac() {
    return n === 1 ? 1 : n * arguments.callee(n - 1)
}

let t1 = window.performance.now()
fac(100)
let t2 = window.performance.now()
console.log('diff: ', t2 - t1, ' ms')

// output: diff: 0.14500000001862645 ms

未完待续...

相关文章
相关标签/搜索