如何在JavaScript中检测互联网速度? [英] How to detect internet speed in JavaScript?

查看:136
本文介绍了如何在JavaScript中检测互联网速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个能够检测用户上网速度并在页面上显示的JavaScript页面?像你的互联网速度是?? / ?? Kb / s

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".

推荐答案

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

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.

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

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>

真正的速度测试服务进行快速比较时,使用大图时显示0.12 Mbps的微小差异。

Quick comparison with "real" speed test service showed small difference of 0.12 Mbps when using big picture.

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

To ensure the integrity of the test, you can run the code with Chrome dev tool throttling enabled and then see if the result matches the limitation. (credit goes to user284130 :))

要记住的重要事项:


  1. 应正确优化和压缩正在使用的图像。如果不是,则Web服务器对连接的默认压缩可能会显示比实际更大的速度。另一种选择是使用不可压缩的文件格式,例如, JPG。 (感谢Rauli Rajande 指出这一点和Fluxine 提醒我

  1. 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)

上面描述的缓存占用机制可能不适用于某些CDN服务器,配置为忽略查询字符串参数,因此更好地设置图像本身的缓存控制标头。 (感谢orcaman for 指出这一点

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

这篇关于如何在JavaScript中检测互联网速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆