Skip to content

Instantly share code, notes, and snippets.

@sliim35
Last active August 26, 2019 07:34
Show Gist options
  • Select an option

  • Save sliim35/562374967a726b74ca3e873c697894fc to your computer and use it in GitHub Desktop.

Select an option

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);
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment