Tuesday, June 7, 2011

Bandwidth detection with javascript

In one of my current projects, I came across a scenario to play a video based on the users downloading bandwidth. The detection should be done with javascript. There is a technique, to load an image of known size and calculating the bandwidth on basis of time taken to load that image. Though this technique is not 100% reliable, this will give an approximate estimate of bandwidth.

Here is the javascript code to find users bandwidth:

var userBandwidth = 0;
var startTime;
var endTime;
var imgSize = 39842;
var loadTimeInSec;

function GetUserBandwidth() {
var testImage = new Image();
testImage.src = "bwtest.jpg";
startTime = (new Date()).getTime();
testImage.onload = CreateDelegate(testImage, DoneWithTest);

function DoneWithTest() {
endTime = (new Date()).getTime();
loadTimeInSec = (endTime - startTime) / 1000;
userBandwidth = (imgSize / loadTimeInSec) / 1024;

Here we are loading an image of size 38Kb and added a delegate on image loaded event. In the call back function, we calculate end time, with that we can calculate the bandwidth of the user.

Check my previous post to add delegate in javascript.

No comments:

Post a Comment