sw.js: A quick guide to the service worker script
sw.js is the service worker script that enables offline support and background tasks in modern web apps. Here's a quick guide to its role and a minimal example.
What sw.js is and how it fits into the web
sw.js is the filename commonly used for a service worker script. It runs in the background, separate from web pages, and is registered by the main page to enable features like offline support, asset caching, and background tasks.
The role of the service worker
The service worker is a script that can intercept network requests, manage caches, and respond to messages. It stays alive in the background even when the page is closed.
How sw.js gets registered
From your page, you call navigator.serviceWorker.register('/sw.js'), which creates a service worker for the current scope and allows it to intercept requests within that scope.
Understanding the service worker
A service worker is a programmable proxy that sits between your web app and the network. It can cache responses, serve requests from the cache, and run tasks in the background.
Scope and lifecycle
The scope of a service worker is determined by where sw.js is located and by the registration. It has a lifecycle with install, activate, and fetch events.
The sw.js lifecycle: install, activate, fetch
Install event
During install, you typically pre-cache key assets so the app can start offline.
Activate event
The activate event runs after installation and can be used to clean up old caches.
Fetch event
The fetch event lets you intercept network requests and serve cached responses when available.
Caching strategies with sw.js
Cache-first
Network-first
Cache-only and stale-while-revalidate
A minimal sw.js example
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/script.js',
'/images/logo.png'
]);
})
);
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request);
})
);
});
Best practices and caveats
- Use versioned caches and clear old ones during activation.
- Consider skipWaiting() and clients.claim() to update clients promptly.
- Be mindful of caching sensitive data; use appropriate strategies and expiration.
- Test offline behavior using browser dev tools.
Debugging and testing sw.js
- Use Chrome DevTools: Application tab > Service Workers and Cache Storage.
- Simulate offline mode in the Network tab and reload.
- Check console logs for registration and errors.
Share This Article
Spread the word on social media
Anne Kanana
Comments
No comments yet. Be the first to share your thoughts!