zoukankan      html  css  js  c++  java
  • js 检测客户端网速

    <!doctype html>
    <html>
    <head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <title>js实现的网速测试方法</title>
    </head>
    <body>
    <script>
    function testBW(fn) {
        var startTime, endTime, fileSize;
        var xhr = new XMLHttpRequest();
    	xhr.timeout=30000;
    	xhr.onerror=function (){
    	    console.log('onerror');
    	}
        xhr.onreadystatechange =function(){
    	   console.log(JSON.stringify(xhr));
            if(xhr.readyState === 2){
                startTime = Date.now();
            }
            if (xhr.readyState === 4) {
                endTime = Date.now();
    			console.log(xhr.readyState+'=='+xhr.responseText.length);
                fileSize = xhr.responseText.length;
                console.log(fileSize);
                var speed = fileSize  / ((endTime - startTime)/1000) / 1024;
                fn && fn(Math.floor(speed)||0)
    			console.log('complete');
            }
    		if(xhr.status === 200) {
                endTime = Date.now();
    			console.log(xhr.readyState+'=='+xhr.responseText.length);
                fileSize = xhr.responseText.length;
                console.log(fileSize);
                var speed = fileSize  / ((endTime - startTime)/1000) / 1024;
                fn && fn(Math.floor(speed)||0)
            }
        }
    	//http://wangsu3s.acc5.com/ping.jpg
    	//http://alyun3s.acc5.com/ping.jpg
    	//http://app-static.acc5.com/app/ping.gif
        xhr.open("GET", "http://app-static.acc5.com/app/ping.gif?rnd=" + Math.random(), true);
        xhr.send();
    }
    
    function callback(speed){
        document.write("<div id='div1'>"+speed + " KB/s</div>");
        console.log(speed + " KB/s");  //215 KB/sec
    }
    testBW(callback);
    
    
    </script>
    </body>
    </html>
    

      

  • 相关阅读:
    OSPF Configuration Examples
    enabling ip forwarding
    LeetCode 153. Find Minimum in Rotated Sorted Array
    洛谷 P1059 明明的随机数
    LeetCode 120. Triangle
    洛谷 P1047 校门外的树(待完善)
    C++万能头文件<bits/stdc++.h>的内容与优缺点
    LeetCode 217. Contains Duplicate
    LeetCode 414. Third Maximum Number
    洛谷 P1540 机器翻译
  • 原文地址:https://www.cnblogs.com/xuan52rock/p/11008679.html
Copyright © 2011-2022 走看看