Skip to content

Instantly share code, notes, and snippets.

@sliim35
Last active August 26, 2019 07:34
Show Gist options
  • Save sliim35/562374967a726b74ca3e873c697894fc to your computer and use it in GitHub Desktop.
Save sliim35/562374967a726b74ca3e873c697894fc to your computer and use it in GitHub Desktop.
Service Worker Cheatsheet

Readme

What is a service worker / Source

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.

Lifecycle

lifecycle

  • The install event is the first event a service worker gets, and it only happens once.
  • A promise passed to installEvent.waitUntil() signals the duration and success or failure of your install.
  • A service worker won't receive events like fetch and push until it successfully finishes installing and becomes "active".
  • By default, a page's fetches won't go through a service worker unless the page request itself went through a service worker. So you'll need to refresh the page to see the effects of the service worker.
  • clients.claim() can override this default, and take control of non-controlled pages.

Example

Prerequisites

  • you need HTTPS

Register a service worker

navigator.serviceWorker.register('/sw.js')
  .then((registration) => {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ', registration.scope);
  }
});

Service worker file

Your service-worker.js file is where all the logic for your service worker implementation would normally go. You'd use a mix of the service worker lifecycle events, the Cache Storage API, and knowledge about your web app's network traffic to create a perfectly crafted service worker, ready to handle all of your web app's requests.

But… that's all for learning later. At this stage, the focus is on observing various service worker events, and getting comfortable using Chrome's DevTools to debug the state of your service worker.

To that end, add in the following code to service-worker.js, which will log messages to the DevTools console in response to various events (but not do much else):

self.addEventListener('install', (event) => {
  console.log('Inside the install handler:', event);
});

self.addEventListener('activate', (event) => {
  console.log('Inside the activate handler:', event);
});

self.addEventListener(fetch, (event) => {
  console.log('Inside the fetch handler:', event);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment