Skip to content

Instantly share code, notes, and snippets.

@UsamaAshraf
Last active May 5, 2018 15:40
Show Gist options
  • Save UsamaAshraf/137d571c83f900f75dc47316586be305 to your computer and use it in GitHub Desktop.
Save UsamaAshraf/137d571c83f900f75dc47316586be305 to your computer and use it in GitHub Desktop.
// service-worker.js
// Changing the cache version will cause existing cached resources to be
// deleted the next time the service worker is re-installed and re-activated.
const CACHE_VERSION = 1;
const CURRENT_CACHE = `your-app-name-cache-v-${CACHE_VERSION}`;
const OFFLINE_PAGE_URL = 'offline/offline.html';
const ASSETS_TO_BE_CACHED = ['offline/offline.css', 'offline/offline.jpg', OFFLINE_PAGE_URL];
self.addEventListener('install', event => {
  event.waitUntil(
  caches.open(CURRENT_CACHE).then((cache) => {
  // addAll() hits all the URIs in the array and caches 
  // the results, with the URIs as the keys.
cache.addAll(ASSETS_TO_BE_CACHED)
.then(() => console.log('Assets added to cache'))
.catch(err => console.log('Error while fetching assets', err));
})
  );
});
self.addEventListener('activate', event => {
  // Delete all caches except for CURRENT_CACHE, thus deleting the previous cache
  event.waitUntil(
  caches.keys().then(cacheNames => {
  return Promise.all(
  cacheNames.map(cacheName => {
  if (cacheName !== CURRENT_CACHE) {
  console.log('Deleting out of date cache:', cacheName);
  return caches.delete(cacheName);
  }
  })
  );
  })
  );
});
self.addEventListener('fetch', (e) => {
  const request = e.request;
  // If it’s a request for an asset of the offline page.
  if (ASSETS_TO_BE_CACHED.some(uri => request.url.includes(uri))) {
  return e.respondWith(
  caches.match(request).then((response) => {
  // Pull from cache, otherwise fetch from the server.
  return response || fetch(request);
  })
  );
  }
let response = fetch(request)
  .then((response) => response)
  .catch(() => caches.match(OFFLINE_PAGE_URL));
e.respondWith(response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment