How to Detect Internet Speed in JavaScript

How to detect internet speed in JavaScript?

It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload event measure how much time passed until that event was triggered, and divide this time in the image file size.

Example can be found here: Calculate speed using javascript

Test case applying the fix suggested there:

//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg";
var downloadSize = 4995374; //bytes

function ShowProgressMessage(msg) {
if (console) {
if (typeof msg == "string") {
console.log(msg);
} else {
for (var i = 0; i < msg.length; i++) {
console.log(msg[i]);
}
}
}

var oProgress = document.getElementById("progress");
if (oProgress) {
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");
oProgress.innerHTML = actualHTML;
}
}

function InitiateSpeedDetection() {
ShowProgressMessage("Loading the image, please wait...");
window.setTimeout(MeasureConnectionSpeed, 1);
};

if (window.addEventListener) {
window.addEventListener('load', InitiateSpeedDetection, false);
} else if (window.attachEvent) {
window.attachEvent('onload', InitiateSpeedDetection);
}

function MeasureConnectionSpeed() {
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}

download.onerror = function (err, msg) {
ShowProgressMessage("Invalid image, or error downloading");
}

startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;

function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
ShowProgressMessage([
"Your connection speed is:",
speedBps + " bps",
speedKbps + " kbps",
speedMbps + " Mbps"
]);
}
}
<h1 id="progress">JavaScript is turned off, or your browser is realllllly slow</h1>

How to measure real time internet speed using Javascript?

As @Abion47 said, "Every download/upload test is going to be some variant of "download/upload some dummy file of known size and time how long it takes to transfer".

Therefore I worked around this problem using fast-speed-test-api. The API did not include much documentation so I included my working example below:

const FastSpeedtest = require("fast-speedtest-api");

const myPromise = fastnetApi();
myPromise.then(res =>{
console.log('it returned:', res);
return res
})

function fastnetApi() {

let speedtest = new FastSpeedtest({
token: "YOUR-TOKEN(CAN BE FOUND IN THE GITHUB DOC)", //**** required
verbose: false, // default: false
timeout: 5000, // default: 5000
https: true, // default: true
urlCount: 5, // default: 5
bufferSize: 8, // default: 8
unit: FastSpeedtest.UNITS.Mbps // default: Bps
});

return speedtest.getSpeed().then(s => {
console.log(`Speed: ${s} Mbps`);
console.log(typeof s)
return s;
}).catch(e => {
console.error(e.message);
});
}

detecting internet speed in Javascript?

I think this is a problem with the behavior how packages are transfered in the web.

I cannot explain it 100% but the transmission start with a lower speed than possible and increases during transfer when possible.
So you will never get the maximum speed when you are doing measuring that way.
You can get near to maximum speed when you are downloading a bigger file (try 5mb) and you will get are more precise result.



Related Topics



Leave a reply



Submit