#angular #pwa #offline #service-worker

Day 22 โ€” Progressive Web Apps (PWA): Offline Support & Installation

๐Ÿ“˜ Day 22 โ€” Progressive Web Apps (PWA): Offline Support & Installation

Zero to Hero โ€” Hands-on Angular Tutorial

Today you will learn:

  • โœ”๏ธ What is a PWA?
  • โœ”๏ธ Adding PWA support (@angular/pwa)
  • โœ”๏ธ The Manifest File (Identity, Icons, Theme Color)
  • โœ”๏ธ The Service Worker (Offline Caching)
  • โœ”๏ธ Cache Strategies (Performance vs Freshness)
  • โœ”๏ธ Handling App Updates (Auto-Update logic)

A PWA allows your website to be installed on a phone/desktop and work without an internet connection. ๐Ÿ“ฑ


๐ŸŸฆ 1. Turn your App into a PWA

Angular makes this trivial. Run one command:

ng add @angular/pwa

This automates several tasks:

  1. Creates manifest.webmanifest (App config).
  2. Creates ngsw-config.json (Caching rules).
  3. Adds icons to src/assets/icons.
  4. Enables Service Worker in app.config.ts.
  5. Updates index.html (Theme color, meta tags).

Note: Service Workers only work in Production mode (or http-server). They do not typically work with ng serve.


๐ŸŸฉ 2. The Manifest File

This file tells the browser โ€œI am an app.โ€

src/manifest.webmanifest:

{
  "name": "My Angular App",
  "short_name": "AngularApp",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone", // ๐Ÿ‘ˆ Hides browser address bar!
  "scope": "/",
  "start_url": "/",
  "icons": [ ... ]
}
  • display: "standalone": Makes it look like a native app.
  • icons: The icon on the userโ€™s home screen.

๐ŸŸง 3. Offline Caching (ngsw-config.json)

By default, Angular caches your HTML, JS, CSS, and Assets. If your server dies, the app still loads! ๐Ÿคฏ

But what about Data (API calls)? You must configure it manually.

ngsw-config.json:

{
  "index": "/index.html",
  "assetGroups": [ ... ], // Caches JS/CSS
  "dataGroups": [
    {
      "name": "api-freshness",
      "urls": [
        "/api/daily-news",
        "/api/stock-prices"
      ],
      "cacheConfig": {
        "strategy": "freshness", // ๐Ÿ‘ˆ Try Network first. Fallback to Cache.
        "maxSize": 100,
        "maxAge": "1h",
        "timeout": "5s" // If network slow > 5s, use cache.
      }
    },
    {
      "name": "api-performance",
      "urls": [
        "/api/products", // Product list rarely changes
        "https://fonts.googleapis.com/**"
      ],
      "cacheConfig": {
        "strategy": "performance", // ๐Ÿ‘ˆ Use Cache FIRST. Update in background.
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ]
}
  • Freshness: For data that changes often (News, Stock Prices).
  • Performance: For static data (Fonts, Images, Product Catalog).

๐ŸŸฅ 4. Notify User of Updates

When you deploy a new version, users might still see the old cached version. Angularโ€™s SwUpdate service handles this.

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Component({...})
export class AppComponent implements OnInit {
  constructor(private swUpdate: SwUpdate) {}

  ngOnInit() {
    if (this.swUpdate.isEnabled) {
      
      // Check for updates
      this.swUpdate.versionUpdates.subscribe(evt => {
        if (evt.type === 'VERSION_READY') {
          // ๐ŸŽ‰ Update found!
          if (confirm('New version available. Load New Version?')) {
            window.location.reload();
          }
        }
      });
      
    }
  }
}

๐ŸŸซ 5. Testing PWA Locally

Since ng serve doesnโ€™t support SW fully:

  1. Build: ng build
  2. Serve: http-server -p 8080 -c-1 dist/my-app/browser
  3. Open Chrome DevTools -> Application Tab.
  4. Look for Service Workers. Check โ€œOfflineโ€ box and refresh the page.
    • If it loads, YOU DID IT! ๐ŸŽ‰

๐ŸŽ‰ End of Day 22 โ€” What You Learned

Today you made your app usable Offline and Installable:

  • โœ”๏ธ Manifest: Configured app Identity.
  • โœ”๏ธ Service Worker: Intercepted network requests.
  • โœ”๏ธ Caching Strategies: Tuned for speed (Performance) vs accuracy (Freshness).
  • โœ”๏ธ SwUpdate: Prompting users to update.

๐Ÿงช Day 22 Challenge

โ€œOffline Wikipediaโ€ (Mock)

  1. Add PWA support.
  2. Create a dataGroup in ngsw-config.json for https://api.github.com/users/*.
  3. Use strategy: Performance.
  4. Build and serve (http-server).
  5. Load your Github Profile in the app.
  6. Turn off WiFi.
  7. Refresh the page. Your profile should still load instantly from cache!