You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Angular Service Worker资源Prefetch状态并提示离线资源加载进度

方案1:监听Angular Service Worker内置状态事件

你可以直接使用@angular/service-worker提供的SwUpdate服务获取预取进程的状态,刚好匹配你需要的启动/结束判定需求:

  • 首先在需要使用状态的组件中注入SwUpdate,注意先判断Service Worker是否启用,避免开发环境报错
import { SwUpdate } from '@angular/service-worker';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  // 可以直接用这两个变量控制加载提示的显隐
  prefetchInProgress = true;
  prefetchCompleted = false;

  constructor(private swUpdate: SwUpdate) {}

  ngOnInit() {
    if (!this.swUpdate.isEnabled) {
      // 开发环境未启用Service Worker时直接标记完成,避免一直显示加载
      this.prefetchInProgress = false;
      this.prefetchCompleted = true;
      return;
    }

    // 监听版本检测事件:此时预取进程已经启动,开始下载配置的prefetch资源
    this.swUpdate.versionDetected.subscribe(() => {
      this.prefetchInProgress = true;
      // 这里可以触发加载提示展示逻辑
    });

    // 监听SW激活事件:此时所有prefetch配置的资源已经全部缓存完成,预取结束
    this.swUpdate.activated.subscribe(() => {
      this.prefetchInProgress = false;
      this.prefetchCompleted = true;
      // 这里可以触发加载提示关闭逻辑
    });

    // 可选:监听预取异常事件,处理资源下载失败的场景
    this.swUpdate.unrecoverable.subscribe(() => {
      this.prefetchInProgress = false;
      // 提示用户离线资源下载失败,检查网络后重试
    });
  }
}

注意:activated事件触发的前提是所有标记为prefetch的资源全部成功下载缓存,完全符合你的离线可用判定标准。

方案2:自定义缓存校验(适合需要精确进度的场景)

如果你需要展示预取进度百分比,可以手动调用浏览器缓存API校验资源缓存状态:

  • 先统计你配置的prefetch资源总数量,存为常量
  • 定时轮询Angular Service Worker的缓存目录,统计已缓存的资源数量计算进度
async getPrefetchProgress() {
  const totalPrefetchAssets = 156; // 自行统计你的预取资源总数量
  let cachedCount = 0;
  const allCaches = await caches.keys();
  // Angular SW的资源缓存命名规则为 ngsw:asset:<应用版本哈希>:<assetGroup名称>
  const assetsCacheName = allCaches.find(name => name.startsWith('ngsw:asset') && name.endsWith('assets'));
  if (assetsCacheName) {
    const assetsCache = await caches.open(assetsCacheName);
    const cachedRequests = await assetsCache.keys();
    cachedCount = cachedRequests.length;
  }
  return Math.round((cachedCount / totalPrefetchAssets) * 100);
}
注意事项
  • 开发环境默认不会启用Service Worker,需要使用ng serve --configuration production或者部署到生产环境后测试相关逻辑
  • 如果预取资源存在404等下载失败的情况,Service Worker会终止激活流程,建议在unrecoverable事件中添加异常提示,避免用户一直等待。

内容的提问来源于stack exchange,提问作者Atul Stha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:48:00