How can I create a JavaScript page that will detect the user’s internet speed and show it on the page? Something like “your internet speed is ??/?? Kb/s”.
Even though this is old and answered, i´d like to share the solution i made out of it 2020
it comes with the flexibility to run at anytime and run a callback if greater and or smaller the specified mbps
testConnectionSpeed:{
imageAddr : "/app/images/test_connection.jpg" , // you have to adjust this
downloadSize : 31291,// and this must match with file above ;)
run:function(mbps_max,cb_gt,cb_lt){
testConnectionSpeed.mbps_max = parseFloat(mbps_max) ? parseFloat(mbps_max) : 0;
testConnectionSpeed.cb_gt = cb_gt;
testConnectionSpeed.cb_lt = cb_lt;
testConnectionSpeed.InitiateSpeedDetection();
},
InitiateSpeedDetection: function() {
window.setTimeout(testConnectionSpeed.MeasureConnectionSpeed, 1);
},
result:function(){
var duration = (endTime - startTime) / 1000;
var bitsLoaded = testConnectionSpeed.downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
if(speedMbps >= (testConnectionSpeed.max_mbps ? testConnectionSpeed.max_mbps : 1) ){
testConnectionSpeed.cb_gt ? testConnectionSpeed.cb_gt() : false;
}else {
testConnectionSpeed.cb_lt ? testConnectionSpeed.cb_lt() : false;
}
},
MeasureConnectionSpeed:function() {
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
testConnectionSpeed.result();
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = testConnectionSpeed.imageAddr + cacheBuster;
}
}
you can then start the test anywhere after you included the snippet above by running the testConnectionSpeed.run(mbps, morefunction, lessfunction)
for example:
testConnectionSpeed.run(1.5, function(){console.log(">= 1.5Mbps")}, function(){console.log("< 1.5Mbps")} )
(the larger the image, the more reasonable the test)