JS监听资源加载失败

3,064 阅读1分钟

可以监听同域或跨域(cdn等)资源加载情况

一、performance.getEntries()

使用performance.getEntries()获取页面所以加载资源,如果资源的decodedBodySize或者transferSize为0,则代表资源加载失败了。

let entries = performance.getEntries();
let failed = entries.filter(item => item.transferSize === 0);

二、监听error事件

<script>
  window.addEventListener('error', function (e) {
    const tag = e.target.localName;
    if (tag === 'link' || tag === 'script') {
      // 错误处理
    }
  //  注意这里必须在捕获阶段才能监听到
  }, true);
</script>