捕捉浏览器资源加载404异常,自动重新加载页面。

/***
 * 监控资源404情况,自动刷新获取最新资源
 */

(function () {
    // 监控404开关
    const openScriptError404: boolean = true;
    if (!openScriptError404) return;

    const _autoReloadContKey: string = 'auto-reload-cont';
    const _reloadMaxCont: number = 5

    // 资源404时自动强刷页面
    window.addEventListener('error', (event) => {
        console.info("error", event, event.target)

        const tag: any = event.target;
        const cont: number = Number(sessionStorage.getItem(_autoReloadContKey) || 0);
        if (cont >= _reloadMaxCont) return;

        // 标记reload次数小于5次
        if (tag.tagName === 'LINK' || (tag.tagName === 'SCRIPT' && !(event instanceof ErrorEvent)) || event?.message?.includes('Failed to load resource')) {
            sessionStorage.setItem(_autoReloadContKey, String(cont + 1))
            location.reload()
        }
    }, true)

    // 动态模块导入错误重载
    window.addEventListener('unhandledrejection', (e) => {
        console.info("error", e, e.reason)

        const message = e?.reason?.message;
        const cont: number = Number(sessionStorage.getItem(_autoReloadContKey) || 0);
        if (cont >= _reloadMaxCont) return;

        if (/(Failed to fetch dynamically imported module:|Failed to load resource)/.test(message)) {
            sessionStorage.setItem(_autoReloadContKey, String(cont + 1))
            location.reload()
        }
    }, true)

    // 3秒后,没有触发,则移除标记
    setTimeout(() => {
        sessionStorage.removeItem(_autoReloadContKey)
    }, 3000)
})()

捕捉到浏览器资源加载404异常,比如js、css资源,自动重新加载页面,每出现一次错误连续至多自动加载5次。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值