shuangmianxiaoQ / study-note

日常学习或工作笔记
6 stars 1 forks source link

常用的性能测量APIs #58

Open shuangmianxiaoQ opened 4 years ago

shuangmianxiaoQ commented 4 years ago

常用性能指标计算

性能APIs实例

  1. 计算一些关键的性能指标
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. 观察长任务
const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
        console.log(entry)
    }
})

observer.observe({entryTypes: ['longtask']})
  1. 页面可见性的状态监听
let vEvent = 'visibilitychange';

if (document.webkitHidden != undefined) {
    // webkit 事件名称
    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);
  1. 用户网络状态监听
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
let type = connection.effectiveType;

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

connection.addEventListener('change', updateConnectionStatus);