perf-reporter.js 2.7 KB
var cookies = require('../cookie');
var reporter = require('./reporter');

var perfKey = '_perfLog';

var resourcePerf = require('./perf/resource'),
    timingPerf = require('./perf/timing');

var perfReporter = {
    init: function(debug) {
        this.debug = debug;
        this.dataList = [];

        resourcePerf.init(this.debug);
        timingPerf.init(this.debug);

        this.report();

        var self = this;

        window.addEventListener && window.addEventListener('load', function() {
            setTimeout(function() {
                self.collect();
            }, 0);
        });
    },

    collect: function() {
        try {
            var timingPerfData = timingPerf.collect();
            var resourcePerfData = resourcePerf.collect();

            this.chunk(timingPerfData);

            for (var i = 0; i < resourcePerfData.length; i++) {
                this.chunk(resourcePerfData[i]);
            }
        } catch(e) {
            if (this.debug) {
                console.log(e);
            }
        }
    },

    getMeta: function() {
        return {
            pt: encodeURIComponent(window.location.href), // url
            ua: encodeURIComponent(navigator.userAgent),  // useragent
            u: reporter.getUid(),                         // uid
            ud: reporter.getUdid(),                       // udid
            rid: reporter.getReqId(),                     // reqId
            r: reporter.getRoute()                        // server route
        }
    },

    jsonConcat: function(object1, object2) {
        for (var key in object2) {
            object1[key] = object2[key];
        }
        return object1;
    },

    write: function(item) {
        var perfList = JSON.parse(cookies(perfKey) || '[]');

        this.jsonConcat(item, this.getMeta());

        perfList.push(item);
        cookies(perfKey, JSON.stringify(perfList));

        if (perfList.length >= 5) {
            this.report();
        }
    },

    report: function() {
        var self = this;
        var perfList = JSON.parse(cookies(perfKey) || '[]');
        var perfStr = reporter.stringify(perfList);

        reporter.report(perfStr, function() {
            self.clear();
        });
    },

    clear: function() {
        cookies(perfKey, '[]');
    },

    chunk: function(item) {
        var self = this;
        this.dataList.push(item);

        function _write() {
            if (self.dataList.length === 0) {
                return
            }

            var data = self.dataList.shift();

            self.write(data);

            setTimeout(_write,  10)
        }

        setTimeout(function() {
            _write();
        }, 10)
    }
};

if (window._perfEnable_) {
    perfReporter.init(true);
}