Adding a Service Worker
Service workers cache static assets and API responses, enabling offline visits and faster repeat loads.
Adding PWA Support
ng add @angular/pwa
This command:
- Installs @angular/service-worker
- Generates ngsw-config.json (cache configuration)
- Creates a web app manifest
- Registers the service worker in app.config.ts
- Adds manifest link to index.html
Service Worker Configuration
// ngsw-config.json
{
"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/**",
"/*.(svg|png|jpg|jpeg|gif|webp)"
]
}
}
],
"dataGroups": [
{
"name": "api",
"urls": ["/api/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "1d"
}
}
]
}
Asset Group Modes
| Mode | Behavior |
|---|---|
prefetch |
Cache all files immediately on first load |
lazy |
Cache files only when first requested |
Data Group Strategies
| Strategy | Behavior |
|---|---|
freshness |
Network first, cache fallback |
performance |
Cache first, network fallback |
Service Worker Lifecycle
Understanding the service worker lifecycle helps you manage updates and caching effectively.
Lifecycle Stages
1. Download — Service worker script downloads
2. Install — Service worker installs and caches assets
3. Activate — Service worker takes control of the page
4. Fetch — Service worker intercepts network requests
5. Update — New service worker version detected
Update Flow
import { SwUpdate } from '@angular/service-worker';
@Component({
selector: 'app-root',
template: `
<div *ngIf="updateAvailable" class="update-banner">
New version available!
<button (click)="update()">Update</button>
</div>
`,
})
export class AppComponent {
private swUpdate = inject(SwUpdate);
updateAvailable = false;
constructor() {
this.swUpdate.versionUpdates.subscribe(event => {
if (event.type === 'VERSION_READY') {
this.updateAvailable = true;
}
});
}
update(): void {
this.swUpdate.activateUpdate().then(() => {
window.location.reload();
});
}
}
Testing Service Workers
Service workers only work in production builds:
# Build for production
ng build --configuration production
# Serve the production build
npx http-server -p 8080 dist/my-app/browser
Offline Verification
- Load the app in Chrome
- Open DevTools → Application → Service Workers
- Check "Offline"
- Reload the page — it should still work from cache
Quiz
1. How do you add a service worker to an Angular app?
2. What is the difference between prefetch and lazy install modes?
3. What is the freshness strategy for data groups?
Flashcards
Question
How to add a service worker?
Click to reveal answer
Answer
ng add @angular/pwa — generates config, manifest, and registration.
Question
prefetch vs lazy?
Click to reveal answer
Answer
Prefetch: cache all immediately. Lazy: cache on first request.
Question
Freshness strategy?
Click to reveal answer
Answer
Network first, cache fallback.
Revision Notes
Key Takeaways
- 1. ng add @angular/pwa adds service worker support
- 2. prefetch caches immediately, lazy caches on demand
- 3. Freshness strategy: network first, cache fallback
- 4. Service workers only work in production builds
Interview Tips
- • Explain the service worker lifecycle
- • Be ready to describe caching strategies
- • Mention update flow and version management
Cheat Sheet
Service Worker Cheat Sheet
Add PWA:
ng add @angular/pwa
Asset groups:
- prefetch: cache all immediately
- lazy: cache on first request
Data strategies:
- freshness: network first, cache fallback
- performance: cache first, network fallback
Update flow:
this.swUpdate.versionUpdates.subscribe(event => {
if (event.type === 'VERSION_READY') {
// Prompt user to update
}
});