Skip to content

Instantly share code, notes, and snippets.

@gauravchl
Last active June 10, 2017 09:09
Show Gist options
  • Save gauravchl/fc49294a0d71d77d0fb803d360421f9b to your computer and use it in GitHub Desktop.
Save gauravchl/fc49294a0d71d77d0fb803d360421f9b to your computer and use it in GitHub Desktop.
Default service worker for github pages
const APP_PREFIX = 'repo-name'
const VERSION = '0.0.0.1'
const CACHE_NAME = APP_PREFIX + VERSION
const URLS = [
'/repo-name/',
'/repo-name/index.html',
'/repo-name/main.css',
'/repo-name/sw.js',
]
self.addEventListener('install', e => e.waitUntil(swInstall()))
self.addEventListener('activate', e => e.waitUntil(swActivate()))
self.addEventListener('fetch', e => e.respondWith(swFetch(e)))
async function swFetch(e) {
console.log('sw[fetch]')
let request = await caches.match(e.request);
return request || fetchAndCache(e.request);
}
async function swInstall() {
console.log('sw[install]')
const cache = await caches.open(CACHE_NAME);
let options = {headers: {'cache-control': 'no-cache'}};
let requests = URLS.map(url => new Request(url, options))
await cache.addAll(requests);
await self.skipWaiting();
}
async function swActivate() {
console.log('sw[activate]')
let keyList = await caches.keys();
let cacheWhitelist = keyList.filter(key => key.indexOf(APP_PREFIX));
cacheWhitelist.push(CACHE_NAME)
return Promise.all(keyList.map(function (key, i) {
if (cacheWhitelist.indexOf(key) === -1) {
console.log('deleting cache : ' + keyList[i] )
return caches.delete(keyList[i])
}
}))
}
async function fetchAndCache(request){
const res = await fetch(request);
const cache = await caches.open(CACHE_NAME);
cache.put(request, res.clone());
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment