Detecting Service Worker Support for PWAs
Learn how to check for Service Worker support, register workers, and implement offline capabilities. Essential for progressive web app development.
Workers
Detailed Explanation
Service Worker Detection
Service Workers are the foundation of Progressive Web Apps (PWAs), enabling offline caching, push notifications, and background sync. They act as a programmable network proxy between the browser and the server.
Detection
const hasServiceWorker = 'serviceWorker' in navigator;
Registration Pattern
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
try {
const registration = await navigator.serviceWorker.register('/sw.js');
console.log('SW registered:', registration.scope);
} catch (error) {
console.error('SW registration failed:', error);
}
});
}
Requirements
- HTTPS required: Service Workers only run on secure origins (HTTPS) or localhost for development.
- Same-origin: The service worker file must be served from the same origin as the page.
- Scope: A service worker controls pages within its scope (the directory where it is registered).
- Lifecycle: Service Workers go through install, activate, and fetch phases with their own update cycle.
Related APIs
Service Workers enable several dependent APIs:
- Cache API (
caches) for offline storage - Push API for push notifications
- Background Sync for deferred requests
- Navigation Preload for faster page loads
Use Case
Required for building offline-first web applications, caching static assets, implementing push notifications, and enabling background data synchronization. Any modern PWA needs Service Worker support as a baseline.