I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clearly distinguish between 3G or Wi-Fi for example, maybe someone can make a more elegant version or even a jQuery plugin.
var arrTimes = [];_x000D_
var i = 0; // start_x000D_
var timesToTest = 5;_x000D_
var tThreshold = 150; //ms_x000D_
var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server_x000D_
var dummyImage = new Image();_x000D_
var isConnectedFast = false;_x000D_
_x000D_
testLatency(function(avg){_x000D_
isConnectedFast = (avg <= tThreshold);_x000D_
/** output */_x000D_
document.body.appendChild(_x000D_
document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)_x000D_
);_x000D_
});_x000D_
_x000D_
/** test and average time took to download image from server, called recursively timesToTest times */_x000D_
function testLatency(cb) {_x000D_
var tStart = new Date().getTime();_x000D_
if (i<timesToTest-1) {_x000D_
dummyImage.src = testImage + '?t=' + tStart;_x000D_
dummyImage.onload = function() {_x000D_
var tEnd = new Date().getTime();_x000D_
var tTimeTook = tEnd-tStart;_x000D_
arrTimes[i] = tTimeTook;_x000D_
testLatency(cb);_x000D_
i++;_x000D_
};_x000D_
} else {_x000D_
/** calculate average of array items then callback */_x000D_
var sum = arrTimes.reduce(function(a, b) { return a + b; });_x000D_
var avg = sum / arrTimes.length;_x000D_
cb(avg);_x000D_
}_x000D_
}
_x000D_