Cache with Network Update
Example on how to use the cache, but always update it with the latest data from the network for subsequent visits.
const cacheName = 'app-cache-v1';
const urlToCache = 'data.json';
// At service worker installation, cache required assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
// Cache the file on installation
return cache.add(urlToCache);
})
);
});
This code sets up a service worker installation event listener to cache the initial `data.json` when the service worker is installed.
self.addEventListener('fetch', (event) => {
event.respondWith(
// Try to get the response from the cache
caches.match(event.request)
.then((response) => {
// Return response from cache, if available
if (response) {
updateCache(event.request); // Update cache with latest network data for next visit
return response;
}
// Fetch the latest data from the network
return fetch(event.request);
})
);
});
This code adds an event listener for fetch events. If the asset is in the cache, it returns the cached response and then updates the cache with the latest data from the network. If not cached, it fetches directly from the network.
function updateCache(request) {
// Open the cache and update the asset
caches.open(cacheName).then((cache) => {
fetch(request).then((response) => {
// Put the newest version in the cache
cache.put(request, response);
});
});
}
This function takes a request, fetches the latest version of the asset from the network, and updates the cache with the new response.