前端analysis | 知其所以然

Angular Service Worker

2025-07-01

Angular Service Worker 使用指南

Angular 提供了内建的 Service Worker 支持,用于构建 PWA(渐进式 Web 应用),实现离线体验、缓存优化和更快的加载速度。

📦 安装与配置

1. 添加 Service Worker 支持

1
ng add @angular/pwa

此命令将自动:

  • 添加 @angular/service-worker
  • 修改 angular.json 构建配置
  • 创建 ngsw-config.json 配置文件
  • index.html 中添加必要的 meta 标签

2. 生产环境构建

Service Worker 仅在生产构建中启用:

1
ng build --prod

构建后会在 dist/ 目录生成以下文件:

  • ngsw-worker.js:Service Worker 主文件
  • ngsw.json:缓存配置文件

3. 注册 Service Worker

app.module.ts 中自动添加:

1
2
3
4
5
6
7
8
9
10
11
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
imports: [
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
})
]
})
export class AppModule {}

⚙️ 配置文件:ngsw-config.json

用于控制缓存行为的核心文件,示例结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": ["/assets/**", "/*.(png|jpg|svg)"]
}
}
],
"dataGroups": [
{
"name": "api-freshness",
"urls": ["/api/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "1h",
"timeout": "10s"
}
}
]
}

属性解释

  • installMode: prefetch | lazy

    • prefetch: 安装时立即缓存
    • lazy: 首次访问时才缓存
  • updateMode: 更新缓存的方式

    • prefetch: 后台下载新版本
  • dataGroups: 用于控制 API 响应缓存(支持 freshness / performance 策略)


🔁 更新检测与提示

Angular 不会自动刷新页面,需手动监听更新:

示例:自动提示用户更新

1
2
3
4
5
6
7
8
9
constructor(private swUpdate: SwUpdate) {
if (swUpdate.isEnabled) {
swUpdate.available.subscribe(() => {
if (confirm('新版本可用,是否刷新以更新?')) {
window.location.reload();
}
});
}
}

🧪 开发调试技巧

  • 使用 Chrome DevTools > Application > Service Workers 面板进行调试
  • 本地需通过 HTTPS 或 localhost 运行
  • 重新部署时务必更新文件哈希或构建资源,否则更新不会触发

📚 参考资源


定制化的 ngsw-config.json 文件,包含:

  • 常见资源的缓存规则(如 CSS/JS、图片、字体、assets)
  • 对后端 API 的缓存策略(支持离线读取 + 更新)
  • 更新策略(后台更新、新版本提醒)
  • 性能与离线体验兼顾的配置

✅ 适用场景(你可以根据需要修改):

  • 应用资源希望首次加载后离线可用
  • 图片等静态资源懒加载缓存
  • API 使用 freshness 策略(优先网络,失败用缓存)
  • 启动页/首页等要尽快预加载
  • 每次部署都更新版本(自动对比文件 hash)

🧩 定制 ngsw-config.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app-shell",
"installMode": "prefetch",
"updateMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(png|jpg|jpeg|svg|webp|woff2|woff|ttf|eot)"
]
}
}
],
"dataGroups": [
{
"name": "api-data",
"urls": [
"https://api.example.com/**"
],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "6h",
"timeout": "10s"
}
},
{
"name": "fallback-api",
"urls": [
"/assets/mock/**"
],
"cacheConfig": {
"strategy": "performance",
"maxSize": 50,
"maxAge": "12h"
}
}
]
}

🔄 更新策略说明

Angular 默认采用 版本对比 + hash 检查 方式更新静态资源:

  • 每次 ng build --prod 会生成新的哈希值
  • 用户访问旧版本时,Service Worker 会在后台拉取新版本
  • 可通过 SwUpdate 监听并提示用户刷新

示例代码(放在 AppComponent 或 CoreService):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { SwUpdate } from '@angular/service-worker';

constructor(private swUpdate: SwUpdate) {
if (this.swUpdate.isEnabled) {
this.swUpdate.versionUpdates.subscribe(evt => {
if (evt.type === 'VERSION_READY') {
const update = confirm('检测到新版本,是否立即刷新?');
if (update) {
window.location.reload();
}
}
});
}
}

⚙️ 进阶优化建议

内容 建议
图片资源缓存 使用 installMode: lazy + updateMode: prefetch
API 缓存策略 freshness 更适合动态内容,失败时用缓存
字体等静态资源 长期缓存,performance 策略
缓存清理 设置 maxSizemaxAge 避免无限增长
多语言版本页面 每种语言单独配置为不同缓存组(可加路径匹配规则)
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏