Clientside Moment Profiling

When developing complex JavaScript applications, it is useful to profile the loading of your pages, so you can better understand the bottlenecks of performance. To the end user, the most important moment is when the browser indicates that the page is finished loading. As developers, it is our job to understand why loading takes so long and how to improve it. Todays article will introduce a simple widget called MomentTracker, which allows you to easily compile a collection of important client-side moments and then output them.

How to do it…

Include the following snippet as the first element in your head element:
var __momentTracker = {
	aMoments: [],

	addCookieHandler: function() {
		YAHOO.util.Event.on(window, unload, function() {
			var oneMinuteLater = new Date();
			oneMinuteLater.setTime((new Date()).getTime() + 60000);
			YAHOO.util.Cookie.set(__momentTracker, new Date(), {expires: oneMinuteLater});
		});
	},

	rollup: function() {
		var lastPageTime = YAHOO.util.Cookie.get(__momentTracker),
			aMoments = __momentTracker.aMoments,
			rs = [],
			i, t1, t2;

		if (lastPageTime) {
			__momentTracker.lastPage = new Date(lastPageTime);
			aMoments.unshift(lastPage);
		}

		for (i=aMoments.length-1; 0ms +  =  + aMoments[i] +  -  + aMoments[i-1]);
		}

		return rs;
	},

	trackMoment: function(sName) {
		__momentTracker[sName] = new Date();
		__momentTracker.aMoments.push(sName);
	}
};
__momentTracker.trackMoment(pageStart);

Then anytime you want to track an important moment, call the trackMoment function with the name you would like to call that moment:

To measure the time between pages, we need to setup a cookie (call this anytime after YAHOO.util.Cookie and YAHOO.util.Event are included):

__momentTracker.addCookieHandler();

And lastly, to output the results call:

Event.on(window, load, function() {
	__momentTracker.trackMoment(afterJavaScript);
	Y.log(__momentTracker.rollup().join("\n"));
});

How it works…

The trackMoment function simply stores a date object, at the moment it is executed. The addCookieHandler function adds an unload event to record when the user leaves the page. The rollup function iterates on all the moments, calculates the difference between them in milliseconds, and then returns the results.

The implementation in this article, uses the YUI Logger module to print the results. However, you could modify the rollup function to suit your needs, and use the results in a more meaningful way. At Mint.com we pass the tracked moments times to the server, where they are aggregated into our performance monitoring system.

Ive put together a quick demo page to show it working.