Javascript 如何检测缓慢的互联网连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6994061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:11:08  来源:igfitidea点击:

How to detect slow internet connections?

javascript

提问by Starx

Currently, most of the popular websites, like google, yahoo detect if the user connection speed is slow and then give a option to load basic version of the website instead of the high end one.

目前,大多数流行的网站,如谷歌、雅虎,都会检测用户连接速度是否慢,然后提供一个选项来加载网站的基本版本而不是高端版本。

What are the methods available to detect slow internet connections?

有哪些方法可用于检测慢速 Internet 连接?

P.S. I think this is achieved through javascript, so I will tag it as a javascript question? However, I am looking for answers oriented more towards PHP, if this is also server related.

PS我认为这是通过javascript实现的,所以我将其标记为javascript问题?但是,我正在寻找更多面向 PHP 的答案,如果这也与服务器有关。

回答by Sam Hanes

You can start a timeoutin an inline script block in <head>, which will be run as soon as it's encountered. You would then cancel the timeoutwhen the loadevent fires. If the timeout ever fires, the page is loading slowly. For example:

您可以在 中的内联脚本块中启动超时<head>,它会在遇到时立即运行。然后,您将在事件触发时取消超时load。如果超时触发,则页面加载缓慢。例如:

<script type="text/javascript">
    var slowLoad = window.setTimeout( function() {
        alert( "the page is taking its sweet time loading" );
    }, 10 );

    window.addEventListener( 'load', function() {
        window.clearTimeout( slowLoad );
    }, false );
</script>

Obviously you would want to replace the alert with something a little more useful. Also note that the example uses the W3C/Netscape event API and thus won't work in Internet Explorer before version 9.

显然,您想用更有用的东西替换警报。另请注意,该示例使用 W3C/Netscape 事件 API,因此无法在版本 9 之前的 Internet Explorer 中运行。

回答by Jules Colle

Here's a full implementation I just completed for a site I'm working on. Felt like sharing it. It uses a cookie to dismiss the message (for people who don't mind that the site takes a long time to load.) The message will show if the page is taking longer than 1 second to load. Best to change this to around 5 seconds or so.

这是我刚刚为我正在处理的网站完成的完整实现。感觉就像分享它。它使用 cookie 来关闭消息(对于那些不介意网站加载时间很长的人)。如果页面加载时间超过 1 秒,消息将显示。最好将其更改为大约 5 秒左右。

The code below should be added right after the opening <head>tag, because it has to be loaded as soon as possible, but it can't appear before the html or head tag, because these tags need to be present in the DOM when the script is run. It's all inline code, so the scripts and styles are loaded before any other external files (css, js or images).

下面的代码应该在开始<head>标签之后添加,因为它必须尽快加载,但不能出现在html或head标签之前,因为脚本运行时这些标签需要出现在DOM中跑。它都是内联代码,因此脚本和样式在任何其他外部文件(css、js 或图像)之前加载。

<style>
    html { position: relative; }
    #slow-notice { width:300px; position: absolute; top:0; left:50%; margin-left: -160px; background-color: #F0DE7D; text-align: center; z-index: 100; padding: 10px; font-family: sans-serif; font-size: 12px; }
    #slow-notice a, #slow-notice .dismiss { color: #000; text-decoration: underline; cursor:pointer; }
    #slow-notice .dismiss-container { text-align:right; padding-top:10px; font-size: 10px;}
</style>
<script>

    function setCookie(cname,cvalue,exdays) {
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname + "=" + cvalue + ";path=/;" + expires;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) return c.substring(name.length,c.length);
        }
        return "";
    } 

    if (getCookie('dismissed') != '1') {
        var html_node = document.getElementsByTagName('html')[0];
        var div = document.createElement('div');
        div.setAttribute('id', 'slow-notice');

        var slowLoad = window.setTimeout( function() {
            var t1 = document.createTextNode("The website is taking a long time to load.");
            var br = document.createElement('br');
            var t2 = document.createTextNode("You can switch to the ");
            var a = document.createElement('a');
            a.setAttribute('href', 'http://light-version.mysite.com');
            a.innerHTML = 'Light Weight Site';

            var dismiss = document.createElement('span');
            dismiss.innerHTML = '[x] dismiss';
            dismiss.setAttribute('class', 'dismiss');
            dismiss.onclick = function() {
                setCookie('dismissed', '1', 1);
                html_node.removeChild(div);
            }

            var dismiss_container = document.createElement('div');
            dismiss_container.appendChild(dismiss);
            dismiss_container.setAttribute('class', 'dismiss-container');

            div.appendChild(t1);
            div.appendChild(br);
            div.appendChild(t2);
            div.appendChild(a);
            div.appendChild(dismiss_container);

            html_node.appendChild(div);


        }, 1000 );

        window.addEventListener( 'load', function() {
            try {
                window.clearTimeout( slowLoad );
                html_node.removeChild(div);
            } catch (e){
                // that's okay.
            }

        });
    }

</script>

The result should look like this:

结果应如下所示:

enter image description here

在此处输入图片说明

Hope it helps.

希望能帮助到你。

回答by Ryan Li

You could listen to two DOM events, DOMContentLoadedand load, and calculate the difference between the time these two events are dispatched.

您可以监听两个 DOM 事件DOMContentLoadedload,并计算这两个事件被分派的时间差。

DOMContentLoadedis dispatched when the DOM structure is ready, but external resources, images, CSS, etc. may not be.

DOMContentLoaded当 DOM 结构准备好时调度,但外部资源、图像、CSS 等可能没有。

loadis dispatched when everything is ready.

load当一切准备就绪时发送。

http://ablogaboutcode.com/2011/06/14/how-javascript-loading-works-domcontentloaded-and-onload/

http://ablogaboutcode.com/2011/06/14/how-javascript-loading-works-domcontentloaded-and-onload/

回答by manikanta

You can get the connection speed by downloading some test resource (image would be more suitable) whose size is known to you (which is easy to get) and measuring the time taken to download it. Keep in mind that testing one time will only gives you the connection speed at that instant. Results may vary from time to time if user is using bandwidth parallel to the image tests. This results in the bandwidth available for your app, which is what we need exactly.

您可以通过下载一些已知大小(易于获取)的测试资源(图像更合适)并测量下载所需的时间来获得连接速度。请记住,测试一次只会为您提供那一刻的连接速度。如果用户使用与图像测试并行的带宽,结果可能会不时变化。这会导致您的应用程序可用的带宽,这正是我们所需要的。

I read somewhere Google does similar trick using some 1x1 grid pixel image for testing the connection speed at the page load and it even shows you something like 'Connection seems slow, try HTML version'... or similar.

我在某处读到谷歌使用一些 1x1 网格像素图像来测试页面加载时的连接速度做了类似的技巧,它甚至向你展示了类似“连接看起来很慢,尝试 HTML 版本”......或类似的东西。

Here is another link describing the same technique - http://www.ehow.com/how_5804819_detect-connection-speed-javascript.html

这是描述相同技术的另一个链接 - http://www.ehow.com/how_5804819_detect-connection-speed-javascript.html

回答by ornanna

Sometimes, your internet connection is slow because you're paying for crappy internet. You need to use network speed testing tools. If what you've measured is close to what you're paying for, then your network is working fine and your internet plan just isn't very fast—the best way to speed it up will be to upgrade. You can use banda larga brasil

有时,您的互联网连接速度很慢,因为您为糟糕的互联网付费。您需要使用网络速度测试工具。如果您测量的结果接近您所支付的费用,那么您的网络运行良好,而您的互联网计划并不是很快——加快速度的最佳方法是升级。你可以使用banda larga brasil