Service Worker là script chạy ở background thread, intercept network request giữa app và network — nền tảng của PWA. Lifecycle: Install (precache assets) → Activate (dọn cache cũ) → Fetch (intercept request).
Caching strategies:
- Cache First — check cache trước, fallback network; cho static assets, fonts (offline-first).
- Network First — fetch network, fallback cache khi offline; cho API cần data fresh.
- Stale-While-Revalidate — serve từ cache ngay, update cache chạy nền; cân bằng tốc độ và độ mới cho data non-critical.
- Cache Only / Network Only — cho precached resources / real-time data.
Khả năng khác:
- Background Sync — queue request fail khi offline, retry khi có mạng (vd submit form offline).
- Push Notifications — nhận push từ server kể cả khi app đóng (cần user permission).
Thực tế dùng Workbox của Google (workbox-strategies, workbox-routing, workbox-precaching) thay vì viết boilerplate tay; vite-plugin-pwa tích hợp Workbox sẵn, tự generate service worker.
Lưu ý: bug cache của Service Worker khó debug — phải update cache version khi deploy; debug qua DevTools Application tab. Bắt buộc HTTPS (trừ localhost).