Skip to content
intermediate Phase 14 · Server-Side Rendering and PWA

Service Workers and Offline Support

Cache static assets and API responses for offline visits.

45m
0 problems
Topic Progress 0%

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:

  1. Installs @angular/service-worker
  2. Generates ngsw-config.json (cache configuration)
  3. Creates a web app manifest
  4. Registers the service worker in app.config.ts
  5. 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

  1. Load the app in Chrome
  2. Open DevTools → Application → Service Workers
  3. Check "Offline"
  4. Reload the page — it should still work from cache

Quiz

1. How do you add a service worker to an Angular app?

Question 1 options

2. What is the difference between prefetch and lazy install modes?

Question 2 options

3. What is the freshness strategy for data groups?

Question 3 options

Flashcards

Question

How to add a service worker?

Answer

ng add @angular/pwa — generates config, manifest, and registration.

Question

prefetch vs lazy?

Answer

Prefetch: cache all immediately. Lazy: cache on first request.

Question

Freshness strategy?

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
  }
});

Continue Learning