Blog>
Snippets

Basic Cache-first Strategy

Example showing how to implement a basic cache-first strategy, where we try to serve content from the cache before attempting to fetch it from the network.
// Register the service worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(function(registration) {
      console.log('Service Worker registered with scope:', registration.scope);
    }).catch(function(error) {
      console.log('Service Worker registration failed:', error);
    });
}
This piece of code checks if the Service Worker API is available in the navigator object and then proceeds to register the service worker found at '/sw.js'. It logs the scope to the console on successful registration, or an error if the registration fails.
// Inside sw.js - the service worker file
self.addEventListener('install', function(event) {
  // Perform install steps
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response
        if (response) {
          return response;
        }

        // IMPORTANT: Clone the request. A request is a stream and
        // can only be consumed once.
        var fetchRequest = event.request.clone();

        // Fetch the data from the network
        return fetch(fetchRequest).then(
          function(response) {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();

            caches.open('my-cache-name').then(function(cache) {
              cache.put(event.request, responseToCache);
            });

            return response;
          }
        );
      })
  );
});
This piece of code sets up the event listeners in the service worker file for the 'install' and 'fetch' events. On a fetch request, it tries to find a match in the cache. If found, it serves the cached response; if not, it fetches the request from the network, then clones and caches the response before returning it to the browser. It also ensures that the response is valid and of type 'basic', which generally denotes a request from our own origin.