我如何创建一个JavaScript页面,将检测用户的互联网速度,并显示在页面上?比如“你的网速是??/??”Kb / s”。


当前回答

小片段:

var speedtest = {};
function speedTest_start(name) { speedtest[name]= +new Date(); }
function speedTest_stop(name) { return +new Date() - speedtest[name] + (delete 
speedtest[name]?0:0); }

使用:

speedTest_start("test1");

// ... some code

speedTest_stop("test1");
// returns the time duration in ms

还可以进行更多的测试:

speedTest_start("whole");

// ... some code

speedTest_start("part");

// ... some code

speedTest_stop("part");
// returns the time duration in ms of "part"

// ... some code

speedTest_stop("whole");
// returns the time duration in ms of "whole"

其他回答

这在某种程度上是可能的,但并不真正准确,其思想是加载具有已知文件大小的图像,然后在其onload事件中测量直到该事件被触发所经过的时间,并将此时间除以图像文件大小。

示例可以在这里找到:使用javascript计算速度

应用修复建议的测试用例:

//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>

快速对比“真实”速度测试服务,在使用大图时,差异很小,为0.12 Mbps。

为了确保测试的完整性,您可以在启用Chrome开发工具节流的情况下运行代码,然后查看结果是否符合限制。(credit to user284130:))

需要记住的重要事项:

The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me) The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself. (thanks orcaman for pointing this out)) The bigger the image size is, the better. Larger image will make the test more accurate, 5 mb is decent, but if you can use even a bigger one it would be better.

好吧,现在是2017年,所以你现在有网络信息API(尽管目前跨浏览器的支持有限)来获得某种估计的下行速度信息:

navigator.connection.downlink

这是以Mbits / sec为单位的有效带宽估计。浏览器根据最近观察到的应用程序层在最近活动连接上的吞吐量进行估计。不用说,这种方法的最大优点是,您不需要下载任何内容,只是为了带宽/速度计算。

你可以看看这个和其他一些相关的属性

由于它的支持有限,并且跨浏览器的实现不同(截至2017年11月),强烈建议详细阅读这篇文章

小片段:

var speedtest = {};
function speedTest_start(name) { speedtest[name]= +new Date(); }
function speedTest_stop(name) { return +new Date() - speedtest[name] + (delete 
speedtest[name]?0:0); }

使用:

speedTest_start("test1");

// ... some code

speedTest_stop("test1");
// returns the time duration in ms

还可以进行更多的测试:

speedTest_start("whole");

// ... some code

speedTest_start("part");

// ... some code

speedTest_stop("part");
// returns the time duration in ms of "part"

// ... some code

speedTest_stop("whole");
// returns the time duration in ms of "whole"

最好使用图像来测试速度。但是如果你必须处理zip文件,下面的代码可以工作。

var fileURL = "your/url/here/testfile.zip";

var request = new XMLHttpRequest();
var avoidCache = "?avoidcache=" + (new Date()).getTime();;
request.open('GET', fileURL + avoidCache, true);
request.responseType = "application/zip";
var startTime = (new Date()).getTime();
var endTime = startTime;
request.onreadystatechange = function () {
    if (request.readyState == 2)
    {
        //ready state 2 is when the request is sent
        startTime = (new Date().getTime());
    }
    if (request.readyState == 4)
    {
        endTime = (new Date()).getTime();
        var downloadSize = request.responseText.length;
        var time = (endTime - startTime) / 1000;
        var sizeInBits = downloadSize * 8;
        var speed = ((sizeInBits / time) / (1024 * 1024)).toFixed(2);
        console.log(downloadSize, time, speed);
    }
}

request.send();

对于小于10MB的文件,这将不能很好地工作。您必须在多次下载尝试中运行聚合结果。

由于Punit S的回答,为了检测动态连接速度的变化,你可以使用以下代码:

navigator.connection.onchange = function () {
 //do what you need to do ,on speed change event
 console.log('Connection Speed Changed');
}