Skip to content

Instantly share code, notes, and snippets.

@Leoooob Leoooob/
Last active Feb 5, 2018

What would you like to do?
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
You can’t perform that action at this time.