Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

常用的性能测量APIs #58

Open
shuangmianxiaoQ opened this issue Oct 12, 2020 · 0 comments
Open

常用的性能测量APIs #58

shuangmianxiaoQ opened this issue Oct 12, 2020 · 0 comments

Comments

@shuangmianxiaoQ
Copy link
Owner

shuangmianxiaoQ commented Oct 12, 2020

常用性能指标计算

  • 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

性能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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant