编程知识 cdmana.com

前端性能监控

根据W3C性能小组引入的新的API(目前IE9以上的浏览器)--window.performance,实现前端性能监控

以下是fast3G情况下数据展示

使用方法:

将下面函数引入到index.html文件 每次切换页面即可读取到信息,最好是放在打包上线后的文件中,这样可以读取dns,tcp解析时间。

各个阶段图示

以下是函数封装

(function () {

    handleAddListener('load', getTiming)

    function handleAddListener(type, fn) {
        if (window.addEventListener) {
            window.addEventListener(type, fn)
        } else {
            window.attachEvent('on' + type, fn)
        }
    }

    function getTiming() {
        try {
            var time = performance.timing;
            var timingObj = {};

            var loadTime = (time.loadEventEnd - time.loadEventStart);

            if (loadTime < 0) {
                setTimeout(function () {
                    getTiming();
                }, 200);
                return;
            }
            // 阶段耗时
            timingObj['DNS解析耗时'] = (time.domainLookupEnd - time.domainLookupStart);
            timingObj['TCP连接耗时'] = (time.connectEnd - time.connectStart);
            timingObj['SSL安全连接耗时'] = (time.connectEnd - time.secureConnectionStart);//针对https
            timingObj['网络请求耗时'] = (time.responseStart - time.requestStart);
            timingObj['数据传输耗时'] = (time.responseEnd - time.responseStart);
            timingObj['DOM解析耗时'] = (time.domInteractive - time.responseEnd);
            timingObj['资源加载耗时, 表示页面中的同步加载资源'] = (time.loadEventStart - time.domContentLoadedEventEnd);
            timingObj['前端onload执行时间'] = (time.loadEventEnd - time.loadEventStart);

            //性能指标(上报字段名)
            timingObj["首次渲染"] = time.responseEnd - time.fetchStart
            // timingObj["首屏时间"] =  first meaningful paint
            timingObj["首次可交互"] = time.domInteractive - time.fetchStart
            timingObj["DOMReady"] = time.domContentLoadedEventEnd - time.fetchStart
            timingObj["页面完全加载"] = time.loadEventStart - time.fetchStart
            timingObj["首包时间"] = time.responseStart - time.domainLookupStart


            for (item in timingObj) {
                console.log(item + ":" + timingObj[item] + '毫秒(ms)');
            }

            console.log(performance.timing);
            console.log(performance);

        } catch (e) {
            console.log(timingObj)
            console.log(performance.timing);
        }
    }
})();


作者:李春静
链接:https://juejin.cn/post/6908977607317028877
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



版权声明
本文为[osc_2g0zdjro]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4301845/blog/4837197

Scroll to Top