解决网页中脚本加载失败方案

748 阅读2分钟

公司项目中,有些用户会因为处于网络差的时候,访问游戏页面,而不能正常进入游戏页面。用户是新用户,且本地没有缓存资源的话,处于网络差时,会存在部分脚本加载失败或游戏里面资源加载失败,而导致页面出现卡在加载页面中。为了提高用户的留存率,需要避免这种问题的出现,以下是列举些解决方案,到时候可用于公司项目中。

1、加载失败原因

当脚本在网页加载过程中未能成功加载时,通常会发生错误。这些错误可能是由各种因素引起的,例如网络连接问题、服务器故障、vpn代理等

2、解决方案

大部份可以重复再加载一次,或者使用不同网络节点的脚本地址作为备用源加载

  • 监听单一脚本

如果页面中只存在一个脚本的话,可以使用onerror进行监听脚本,同时使用备用的脚本进行替换加载 eg:其中script11是不存在脚本,script1是存在脚本进行测试

alert("script1");//script1脚本内容
<script>
    function loadBackup() {
        alert(2);
        var script = document.createElement('script');
        script.src = 'http://127.0.0.1:5500/script1.js';
        document.head.append(script);
    }
</script>
<script src="http://127.0.0.1:5500/script11.js" onerror="loadBackup()"></script>
  • 多脚本处理

如果页面存在多个脚本的话,可以通过全局监听error事件,需要记录对应脚本重试次数,以及只能重试几次

注意的是:

1、error事件只能在捕获阶段中使用
2、加载失败资源很多,script 脚本、css 样式文件、img 图片、background-img 背景图,需要过滤
3、当加载失败要阻止页面继续执行,避免因为依赖关系而继续引发错误,可以使用document.write去阻止
console.log("script1");//script1脚本
console.log("script2");//script2脚本
console.log("script3");//script3脚本
    <script>
        const domains=[
            "minigame",
            "minigame1",
            'localhost:5500'
        ]
        const maxRetry=3;
        const retryInfo={};
        window.addEventListener("error",(event)=>{
            const ele=event.target;
            if (ele.tagName==="SCRIPT"&&!(event instanceof ErrorEvent)) {
               const url=new URL(ele.src);
               if (!retryInfo[url.pathname]) {
                    retryInfo[url.pathname]={
                        times:0,
                        nextIndex:0
                    }
               }
               const info =retryInfo[url.pathname];
               if (info.times< maxRetry) {
                   url.host = domains[info.nextIndex];
                   document.write(`<script src="${url.toString()}">\<\/script>`);
                   info.times++;
                   info.nextIndex = (info.nextIndex + 1) % domains.length;
               }
            }
        },true)
    </script>
    <script src="http://a/script1.js"></script>
    <script src="http://localhost:5500/script2.js"></script>
    <script src="http://a/script3.js"></script>
    <script>
        console.log("end")
    </script>

最终执行结果: 其中只有localhost才能正常加载脚本,添加的script元素如图所示

image.png

控制台输出内容如图所示

image.png

参考