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) => {
            .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) => {
        // Try to get the response from the cache
            .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 => {
        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.