How to detect internet speed in JavaScript?

前端 未结 9 1603
萌比男神i
萌比男神i 2020-11-22 01:56

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

9条回答
  •  天涯浪人
    2020-11-22 02:33

    I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clearly distinguish between 3G or Wi-Fi for example, maybe someone can make a more elegant version or even a jQuery plugin.

    var arrTimes = [];
    var i = 0; // start
    var timesToTest = 5;
    var tThreshold = 150; //ms
    var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server
    var dummyImage = new Image();
    var isConnectedFast = false;
    
    testLatency(function(avg){
      isConnectedFast = (avg <= tThreshold);
      /** output */
      document.body.appendChild(
        document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)
      );
    });
    
    /** test and average time took to download image from server, called recursively timesToTest times */
    function testLatency(cb) {
      var tStart = new Date().getTime();
      if (i
                    
                    0
                  
                       
                    
                   讨论(0)
                  
                                                      
                  
                  
提交回复
热议问题