捕捉浏览器资源加载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次。

相关推荐

  1. vue 弹出框组件重复打开时,资源重新

    2024-03-27 10:16:02       29 阅读
  2. 同步异步、延迟、预的区别

    2024-03-27 10:16:02       64 阅读
  3. 微信小程序重新当前页面、刷新当前页面

    2024-03-27 10:16:02       40 阅读
  4. vue 异步组件

    2024-03-27 10:16:02       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 10:16:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 10:16:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 10:16:02       82 阅读
  4. Python语言-面向对象

    2024-03-27 10:16:02       91 阅读

热门阅读

  1. 如何获取iOS手机上的APP崩溃日志?

    2024-03-27 10:16:02       34 阅读
  2. 22套软件研发文档模板下载(实用版)

    2024-03-27 10:16:02       40 阅读
  3. 【vue】computed和watch的区别和应用场景

    2024-03-27 10:16:02       43 阅读
  4. 机器学习:智能时代的核心引擎

    2024-03-27 10:16:02       45 阅读
  5. NIO与AIO

    NIO与AIO

    2024-03-27 10:16:02      34 阅读
  6. Element Plus快速入门及常用组件

    2024-03-27 10:16:02       39 阅读
  7. 北航2023年考研机试题

    2024-03-27 10:16:02       41 阅读