Instantly share code, notes, and snippets.

@Leoooob /README.md
Last active Feb 5, 2018

Embed
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:

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

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 = [
"/",
"/css/style.css",
"/js/main.js"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
// if one item cannot be added to the cache
// the whole operation will fail.
return cache.addAll(myCache);
})
.catch((error) => {
console.error(error);
return false;
})
);
});
self.addEventListener("activate", (event) => {
var cacheWhitelist = [cacheName];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
// 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) => {
event.respondWith(
caches.match(event.request)
.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