前端根据服务器访问速度自动分配最优线路
2024年11月04日 28

代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自动分配最优线路</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style type="text/css">
    #loadingwrapper .loading-mask{background:#080915;position:fixed;z-index:1000;top:0;right:0;left:0;bottom:0;}
    #loadingwrapper .loading-box-s{position:absolute;top:50%;left:50%;z-index:5000;text-align:center;width:100%;transform:translate(-50%, -50%);background:#080915;border-radius:5px; }
    #loadingwrapper .loader-cicle{position:relative;width:50px;height:50px;margin-top:15px;margin-bottom:15px;border-radius:50%;display:inline-block;vertical-align:middle;border:7px double #bd5837;-webkit-animation:ball-turn 1s linear infinite;animation:ball-turn 1s linear infinite;}
    #loadingwrapper .loading-text{color: #c3c3c3;}
    #loadingwrapper .loader-cicle::before{content: "";position:absolute;width:10px;height:10px;background:#bd5837;border-radius:50%;bottom:0;right:30px;}
    #loadingwrapper .loader-cicle::after{content: "";position:absolute;width:10px;height:10px;background:#bd5837;border-radius:50%;left:30px;top:0;}
    @keyframes ball-turn{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg);}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg);}}
    </style>
</head>
<body>
<div id="loadingwrapper">
    <div class="loading-mask"></div>
    <div class="loading-box-s">
        <div class="loader-cicle"></div>
        <p class="loading-text">正在为您选择最佳线路,请稍后.....</p>
    </div>
</div>
<script type="text/javascript">
    let ips = [
        '192.168.12.1',
        '192.168.12.2',
        '192.168.12.3',
        '192.168.12.4',
        '192.168.12.5',
    ];//线路地址
    let source = '静态请求资源

    let arr = [];
    for(let ip of ips){
        arr.push(
            new Promise(function(resolve, reject) {
                let startTime, endTime, fileSize;
                let xhr = new XMLHttpRequest();
                xhr.onreadystatechange = () => {
                    if(xhr.readyState === 2){
                        startTime = Date.now();
                    }
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        endTime = Date.now();
                        fileSize = xhr.responseText.length;
                        setTimeout(resolve, endTime-startTime, ip);
                    }
                }
                xhr.open("GET", source, true);
                xhr.send();
                
            })
        );
    }

    Promise.race(arr).then(function(value) {
      console.log(value);
      location.href= value;    //跳转最优线路
    });
    
</script>
</body>
</html>

- End -




0 条评论
  • 表情
  • 游客你好,回复内容需要 登录 查看!