Skip to content

Instantly share code, notes, and snippets.

Last active February 5, 2018 12:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Leoooob/d7e8245ef07e4807fd3ec69b413e9379 to your computer and use it in GitHub Desktop.
Basic Service Worker implementation

Service Worker template

To implement this service worker in your project, you must copy the service-worker.js file to the root directory of the webapp/web page. You must then amend your index.html to contain the following script tag:

  // This makes sure that Service Workers are supported before registering.
  if ('serviceWorker' in navigator) {
      .then((registration) => {
        console.log(`Service Worker Registered at scope: ${registration.scope}`);
      .catch((error) => {
        console.error(`Service Worker failed registration: ${error}`);

You can check to see if your service worker is registering by opening the webapp/web page in Chrome, opening the Dev Tools and navigating to the 'Application' tab and selecting the 'Service Worker' heading.

var cacheName = "my-cache";
// list of static assets
var myCache = [
self.addEventListener("install", (event) => {
.then((cache) => {
// if one item cannot be added to the cache
// the whole operation will fail.
return cache.addAll(myCache);
.catch((error) => {
return false;
self.addEventListener("activate", (event) => {
var cacheWhitelist = [cacheName];
caches.keys().then((cacheNames) => {
return Promise.all( => {
// if our cache is out of date, delete it!
// just update the name of your cache to triger this update
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
self.addEventListener('fetch', (event) => {
.then(response => {
return response || fetch(event.request);
.catch(error => {
return error;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment