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

var perfKey = '_perfLog';

var navigatorPerf = require('./perf/navigator'),
    resourcePerf = require('./perf/resource'),
    screenPerf = require('./perf/screen'),
    timingPerf = require('./perf/timing');

var perfReporter = {
    init: function() {
        navigatorPerf.init();
        resourcePerf.init();
        screenPerf.init();
        timingPerf.init();

        this.report();
    },
    collect: function() {
        var navPerfData = navigatorPerf.collect();
        var screenPerfData = screenPerf.collect();
        var timingPerfData = timingPerf.collect();
        var resourcePerfData = resourcePerfData.collect();

        this.write(navPerfData);
        this.write(screenPerfData);
        this.write(timingPerfData);
        this.write(resourcePerfData);
    },
    write: function(item) {
        var perfList = JSON.parse(cookies(perfKey) || '[]');

        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, '[]');
    }
};

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