Home >Web Front-end >JS Tutorial >How Can I Estimate My Internet Speed Using JavaScript?
JavaScript provides a way to estimate a user's internet speed, although it's important to note that the results may not be highly accurate.
The concept involves loading an image with a known file size and measuring the time it takes to load. By dividing the time taken by the image file size in bytes, an estimate of the internet speed can be obtained.
An example can be found at the link provided below:
This modified test case incorporates a fix to address a potential issue:
// EXAMPLE ONLY. USE YOUR OWN IMAGE! var imageAddr = "https://upload.wikimedia.org/wikipedia/commons/3/3a/Bloemen_van_adderwortel_%28Persicaria_bistorta%2C_synoniem%2C_Polygonum_bistorta%29_06-06-2021._%28d.j.b%29.jpg"; var downloadSize = 7300000; // bytes function ShowProgressMessage(msg) { // Display progress messages on the console and a progress element on the page. 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) { oProgress.innerHTML = (typeof msg == "string") ? msg : msg.join("<br />"); } } 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" ]); } }
In the HTML, include an element with the ID "progress":
<h1>
The above is the detailed content of How Can I Estimate My Internet Speed Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!