Service Worker là JavaScript running trong background thread, intercept network requests giữa app và network — foundation của PWA.
- Lifecycle: Install (cache precache assets) → Activate (cleanup old caches) → Fetch (intercept requests).
- Caching strategies: Cache First (check cache trước, fallback network — offline-first, dùng cho static assets, icon fonts); Network First (fetch từ network, fallback cache nếu offline — dùng cho API calls cần fresh data); Stale-While-Revalidate (serve từ cache immediately, fetch từ network để update cache background — balance speed và freshness, tốt cho non-critical data); Cache Only (chỉ cache, không network — precached resources); Network Only (không cache — real-time data).
- Background Sync: queue failed requests khi offline, retry khi network available — ví dụ submit form offline.
- Push Notifications: receive push messages từ server kể cả khi app không open — cần permission từ user.
- Workbox từ Google: abstraction layer cho Service Worker strategies — workbox-strategies, workbox-routing, workbox-precaching; tránh viết Service Worker boilerplate thủ công. vite-plugin-pwa tích hợp Workbox với Vite, tự động generate service worker.
- Lưu ý: Service Worker cache bugs khó debug — phải explicitly update cache version khi deploy; chrome://serviceworker-internals để debug.
- HTTPS required (localhost exception).
A Service Worker is JavaScript running in a background thread that intercepts network requests between the app and the network — the foundation of PWAs.
- Lifecycle: Install (cache precache assets) → Activate (clean up old caches) → Fetch (intercept requests).
- Caching strategies: Cache First (check cache first, fallback to network — offline-first, use for static assets and icon fonts); Network First (fetch from network, fallback to cache if offline — use for API calls that need fresh data); Stale-While-Revalidate (serve from cache immediately, fetch from network to update cache in the background — balances speed and freshness, good for non-critical data); Cache Only (cache only, no network — for precached resources); Network Only (no caching — for real-time data).
- Background Sync: queues failed requests while offline and retries when the network is available — e.g., submitting a form offline.
- Push Notifications: receive push messages from the server even when the app is not open — requires user permission.
- Workbox from Google: abstraction layer for Service Worker strategies — workbox-strategies, workbox-routing, workbox-precaching; avoids writing Service Worker boilerplate by hand. vite-plugin-pwa integrates Workbox with Vite and automatically generates the service worker.
Pitfall: Service Worker cache bugs are hard to debug — you must explicitly update the cache version on deploy; use chrome://serviceworker-internals to debug.