Service workers - jaredgorski.org

Back to notes

Service workers

Keywords: web development, websites, offline, static files, caching
Date:
  • Service workers are pieces of code run by browsers in the background, independent from running the current website

    • allow for background services:
      • realtime notifications
      • synchronization of data
      • background caching for offline viewing
    • created to solve problems with the AppCache API
    • can't manipulate the DOM directly, but can use the postMessage interface to communicate with the webpage which can manipulate the DOM
    • programmable network proxy, so it can handle requests to and from the webpage
    • does not maintain a persistent global state since it's terminated when not in use, but can use the indexedDB API if needed
    • operates on its own lifecycle:
      • installation
        • cache static assets
        • if any static assets fail to download and cache, installation fails and the service worker doesn't start (waits till next time)
      • activation
        • handle old caches
      • cycle between idle and fetch/message states
    • FYI:
  • example code for registering a service worker:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.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);
    });
  });
}

Source: https://developers.google.com/web/fundamentals/primers/service-workers