Blog>
Snippets

Implementing Service Workers for Caching

Showcase how to register a service worker in Angular and how to cache the application shell for offline access.
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}
This code checks if the current browser supports service workers and if so, registers the service worker script located at '/service-worker.js' when the window loads. Successful or failed registration attempts are logged to the console.
// In the service-worker.js file
self.addEventListener('install', function(event) {
  var CACHE_NAME = 'my-site-cache-v1';
  var urlsToCache = [
    '/',
    '/styles/main.css',
    '/script/main.js'
  ];

  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});
This code represents the 'install' event listener inside the 'service-worker.js' file. It creates a cache called 'my-site-cache-v1' and adds an array of URLs to be cached upon the installation of the service worker. The event.waitUntil() method is used to extend the lifetime of the install event until the caching process is complete.
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});
This code adds an event listener for fetch events to the service worker. When the browser requests a resource, the service worker intercepts it with 'event.respondWith()' and attempts to match the request in the cache. If there is a match (cache hit), it returns the cached response; otherwise, it fetches the resource from the network.