Caching Methods (Cache API) in Service Workers
Caching Methods (Cache API) in Service Workers
Service Workers allow you to manage resource caching using the Cache API. This JavaScript interface gives us access to the browser's cache where we can store HTML, CSS, JavaScript, images, and more.
Example: Pre-caching resources in the install event
const CACHE_NAME = 'site-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/styles.css',
'/main.js',
'/fallback.html',
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(urlsToCache);
})
);
});
Example: Responding to requests from cache or network in the fetch event
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
// If found in cache, return it
if (response) {
return response;
}
// If not in cache, fetch from network and store in cache
return fetch(event.request).then(networkResponse => {
return caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
});
})
);
});
Caching strategies:
Choosing the right strategy is important depending on the application type. For example, content websites might benefit from cache-first, while applications requiring fresh data might prefer network-first.