Learn the concept
Caching Strategies
Service workers intercept network requests enabling offline support and advanced caching. Strategies include Cache First (fast, stale risk), Network First (fresh, slow), Stale While Revalidate (best UX), and Cache Only/Network Only for specific needs.
Service Worker Capabilities:
Caching Strategies:
Cache First: Check cache, fallback to network
Network First: Try network, fallback to cache
Stale While Revalidate: Serve cache, update in background
Cache Only: Only from cache
Network Only: Never cache
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered:', registration.scope);
})
.catch(error => {
console.log('SW registration failed:', error);
});
}
// sw.js - Service Worker
const CACHE_NAME = 'app-cache-v1';
const ASSETS = [
'/',
'/index.html',
'/styles.css',
'/app.js',
'/offline.html'
];
// Install - cache assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(ASSETS))
.then(() => self.skipWaiting())
);
});
// Activate - clean old caches
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(name => name !== CACHE_NAME)
.map(name => caches.delete(name))
);
})
);
});Using a service worker with a 'Cache First' strategy for static assets and an 'Offline-first' approach for application data, ensuring users can access core functionality even without a network connection.
Implementing a 'Stale While Revalidate' caching strategy for article content, where users instantly see cached content, and the service worker fetches fresh content in the background for future visits.
Leveraging Workbox to manage different caching strategies for various asset types (images, CSS, JavaScript, API responses), ensuring optimal performance, cache expiry, and efficient updates for dynamic product catalogs.
Develop a simple To-Do list application that registers a service worker to cache its HTML, CSS, and JavaScript, allowing it to be fully functional offline.
Build a small application that fetches data from an API and uses a service worker with the 'Stale While Revalidate' strategy to cache the API responses, demonstrating instant loading of stale data and background updates.
Starbucks' Progressive Web App uses service workers extensively to provide an app-like experience on the web. It caches menus, stores, and order information, allowing users to browse and even place orders (which syncs when online) while offline.
Google Maps utilizes service workers to offer offline map access and improve loading times. When a user views an area, map tiles and routing data can be cached, making subsequent access faster and enabling navigation without an active internet connection.