杨小杰博客提供免费教程下载和网站搭建技术教程,主要分享和发布网站源码,致力创造一个高质量网络资源教程的分享平台

js输出网站加载耗时详细列表

Young小杰2018-6-26 10:54网站搭建(1)276查询中……小标签: 网站搭建技术教程 javascript

一个开源js,能够轻松输出网页加载耗时详情


<script>
    var times = function() {
        var timing = performance.timing;
    var loadTime = timing.loadEventEnd - timing.navigationStart;/*过早获取时,loadEventEnd有时会是0*/
    if(loadTime <= 0) {
        setTimeout(function(){
            times();
        }, 200);
        return;
    }
    var readyStart = timing.fetchStart - timing.navigationStart;
    var redirectTime = timing.redirectEnd  - timing.redirectStart;
    var appcacheTime = timing.domainLookupStart  - timing.fetchStart;
    var unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart;
    var lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart;
    var connectTime = timing.connectEnd - timing.connectStart;
    var requestTime = timing.responseEnd - timing.requestStart;
    var initDomTreeTime = timing.domInteractive - timing.responseEnd;
    var domReadyTime = timing.domComplete - timing.domInteractive; /*过早获取时,domComplete有时会是0*/
    var loadEventTime = timing.loadEventEnd - timing.loadEventStart;

    var allTimes = [
    { "描述": "准备新页面时间耗时", "时间(ms)": readyStart },
    { "描述": "redirect 重定向耗时", "时间(ms)": redirectTime },
    { "描述": "Appcache 耗时", "时间(ms)": appcacheTime },
    { "描述": "unload 前文档耗时", "时间(ms)": unloadEventTime },
    { "描述": "DNS 查询耗时", "时间(ms)": lookupDomainTime },
    { "描述": "TCP连接耗时", "时间(ms)": connectTime },
    { "描述": "request请求耗时", "时间(ms)": requestTime },
    { "描述": "请求完毕至DOM加载", "时间(ms)": initDomTreeTime },
    { "描述": "解释dom树耗时", "时间(ms)": domReadyTime },
    { "描述": "load事件耗时", "时间(ms)": loadEventTime },
    { "描述": "从开始至load总耗时", "时间(ms)": loadTime }
    ];
    console.table(allTimes);
};
window.onload = times;
</script>
把这段js加到head标签或者js文件中,之后在控制台就能看到所有的加载耗时,总耗时是相当准确的,其他的参考即可


js加载时间.png




评论:

冷逸丶 SouGou Browser 2.X Windows 7广东省东莞市 移动 2018-07-08 10:13
打卡成功,现在时间:10点13分记得每天坚持打卡哦!
对方不想跟你说话并向你丢了一朵小黄花@(献花)
你的文章写的太好啦,赞一个@[真棒]

发表评论: