监听js文件加载失败重新加载

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script>
    const domains = ['xxxxx.net', 'www.baidu.com', 'xxxx.xxx.com'];
    const maxRetry = 3;
    const retryInfo = {
      
      };
    window.addEventListener('error', (e) => {
      
      
      const tag = e.target;
      if (tag.tagName === 'SCRIPT' && !(e instanceof ErrorEvent)) {
      
      
        const url = new URL(tag.src);
        if (!retryInfo[url.pathname]) {
      
      
          retryInfo[url.pathname] = {
      
      
            times: 0,
            nextIndex: 0
          };
        }
        const info = retryInfo[url.pathname];
        if (info.times >= maxRetry) {
      
      
          return
        }
        const script = document.createElement('script');
        document.write(`<script src="${ 
        url.toString()}">\<\/script>`);
        url.host = domains[info.nextIndex];
        script.src = url.toString();
        document.body.insertBefore(script, tag);
        info.times++;
        info.nextIndex = (info.nextIndex + 1) % domains.length;
      }
    }, true)
  </script>
</head>

<body>
  <script src="http://statics1.easyliao.com/web/project/env_loginUrl.js"></script>
  11
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_43553701/article/details/130206317