Detect Internet Speed with JavaScript
Many applications require the ability to measure the user's internet speed. While it's not always accurate, it can provide a helpful indication of the user's connectivity.
Approach
The solution involves loading an image with a known file size and calculating the speed based on the time taken to load it. This is done by:
Example
The following code provides an implementation of this approach:
var imageAddr = "https://example.com/image.png"; var downloadSize = 7300000; //bytes 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; //seconds 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:"); ShowProgressMessage(speedBps + " bps"); ShowProgressMessage(speedKbps + " kbps"); ShowProgressMessage(speedMbps + " mbps"); } }
The above is the detailed content of How Can I Measure Internet Speed Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!