resource.js 2.71 KB
var resourceReporter = {
    init: function(debug) {
        this.enable = true;
        this.debug = debug;

        if (!('performance' in window) ||
            !('getEntriesByType' in window.performance) ||
            !(window.performance.getEntriesByType('resource') instanceof Array)
        ) {
            this.enable = false;
            return;
        }

        this.whiteList = [/^https:\/\/img\d*.static.yhbimg.com/, /^https:\/\/cdn.yoho.cn/];
    },

    print: function() {
        var debug = document.getElementById("debug");
        var output = this.formatDebugInfo();

        if (!debug) {
            var divTag = document.createElement("div");
            divTag.id = "debug";
            divTag.innerHTML = output;
            document.body.appendChild(divTag);
        } else {
            debug.innerHTML += output;
        }
    },

    formatDebugInfo: function() {
        var debuginfo = "<p>resource object: <br/>";
        var data = this.getData();

        for (var i = 0; i < data.length; i++) {
            debuginfo += JSON.stringify(data[i], null, 2) + "<br/>";
        }
        debuginfo += "</p>";
        return debuginfo
    },

    filter: function(url) {
        for (var i = 0; i < this.whiteList.length; i++) {
            if (this.whiteList[i].test(url)) {
                return true;
            }
        }

        return false;
    },

    getData: function() {
        var resources = window.performance.getEntriesByType('resource');
        var resourceList = [];

        for (var obj in resources) {
            var domObj = resources[obj];

            if (!this.filter(domObj.name)) {
                continue;
            }

            resourceList.push({
                tp: 'resource', // 资源
                dtp: domObj.entryType,                                                  // 资源
                id: domObj.name || 'unknown',                                          // 资源 url
                rtp: domObj.initiatorType || 'unknown',                                 // 资源类型 img script
                dt: Math.floor(domObj.domainLookupEnd - domObj.domainLookupStart || 0), // DNS 时间
                tt: Math.floor(domObj.connectEnd - domObj.connectStart || 0),           // tcp 时间
                rt: Math.floor(domObj.responseEnd - domObj.responseStart || 0),        // 下载 时间
                rrt: Math.floor(domObj.responseEnd - domObj.fetchStart || 0)            // 总时间
            })
        }

        return resourceList;
    },

    collect: function() {
        if (!this.enable) {
            return;
        }

        if (this.debug) {
            this.print();
        }

        return this.getData();
    }
};

module.exports = resourceReporter;