Tuesday, August 5, 2008

Performance monitoring web applications with JavaScript

As end users, we often complain about slow web applications, and the same complaint is fired by the user towards us as web application developer. Most used monitoring solutions are based on some request filter implementation, where the server logs the timestamps of the incoming request and outgoing response. This works fine and provides good insight how much time we spend at the application server.

But how do we monitor the delay between the browser and the server, consisting out many multiple firewalls, proxies and many other slow network nodes? Especially when the browser machine is connected to internet directly, without some kind of corporate LAN where you could introduce a monitoring proxy?

After a bit of brainstorming with a smart colleague (thanks Marc), I found a very simple solution based on JavaScript. It catches browser navigation events using the load and unload events and stores the timestamps in a HTTP cookie variable. It does NOT work for asynchronous AJAX events, nor for separately loaded images, but it works well enough for us.


function enterPage() {
var endTime = new Date().getTime()
var timeIndex = document.cookie.indexOf("exitTime=")
var endPoint = document.cookie.indexOf(";", timeIndex)
var startTime = document.cookie.substring(timeIndex + 9, endPoint)
var duration = endTime - startTime
document.cookie = "duration=" + duration + ";"
}

function exitPage() {
var startTime = new Date().getTime()
document.cookie = "exitTime=" + startTime + ";"
}

<body onload="enterPage()" onunload="exitPage()">
my example page
</body>


The browser stores the load duration time in a cookie after the new page is rendered, and posts the cookie to the server in next HTTP request. Since we use J2EE at the server, we simply use the HttpServletRequest.getCookies() method to extract the value.

HTML events
JavaScript and Cookies