Last Updated: September 09, 2019
·
463
· tonyrain

Simple UIProfiler with user timing API

Everybody knows that client side performance in web development means a lot today. There are a lot of libraries to measure application speed.

Today, I would like to talk about HTML5 user timing API basics to measure execution time. To profile events with user timing API we have two great functions:

// get us an ability to mark time point
window.performance.mark('Event started tag');

// allow us to measure time between two event
window.performance.measure('Event measured tag', 'Event started tag', 'Event ended tag');

To get info of measurment or marks we should use this function:

var performanceMarks = window.performance.getEntriesByType('mark'),
      performanceMeasurments = window.performance.getEntriesByType('measure');

Okay, this way lets write some simple UIProfiler based on Singleton, Facade and Module pattern:

var UIProfiler = (function(){
    var instance,
        notSupportedMessage = 'User Timing API is not available...';

    var createTimer = function () {

        var getTimeFromNavigationStart = function() {
            return window.performance.now();
        };

        var startMeasure = function(markName) {
            window.performance.mark(markName + ' started');
        };

        var endMeasure = function(markName) {
            window.performance.mark(markName + ' ended');
        };

        var getMeasurements = function(markName) {
            window.performance.measure(markName + ' measured', markName + ' started', markName + ' ended');
            return window.performance.getEntriesByName(markName + ' measured')[0];
        };

        return {
            getTimeFromNavigationStart: function(){
                return getTimeFromNavigationStart();
            },
            startMeasure: function(markName) {
                startMeasure(markName);
            },
            endMeasure: function(markName) {
                endMeasure(markName);
            },
            getMeasurements: function(markName) {
                var time = getMeasurements(markName);
                return time.duration;
            }
        };
    };

    return {
        getInstance: function() {
            if (window.performance == null) {
                throw new Error(notSupportedMessage);
            }

            if (!instance) {
                instance = createTimer();
            }

            return instance;
        }
    }
})();

This is that. Don't forget to use new HTLM5 features ;)

P.S. github link