Skip to content

Instantly share code, notes, and snippets.

@panayotoff
Last active November 15, 2016 23:08
Show Gist options
  • Save panayotoff/304782f4e339847350ae2f7928dbb069 to your computer and use it in GitHub Desktop.
Save panayotoff/304782f4e339847350ae2f7928dbb069 to your computer and use it in GitHub Desktop.
Service Worker - custom strategy
let cacheVersion = 10;
let apiCacheName = 'api';
let staticCacheNamespace = 'static';
let staticCacheName = staticCacheNamespace + '-' + cacheVersion;
let staticFiles = [
'/',
'/index.html',
'/css/style.css',
'/js/pwa.js'
];
const apiUrl = 'http://localhost:5757/data/data.json';
//--------------------------------------------------------------
// Installation
//--------------------------------------------------------------
self.addEventListener('install', onInstall);
function onInstall(event) {
event.waitUntil(caches.open(staticCacheName).then(function (cache) {
return cache.addAll(staticFiles);
}));
}
//--------------------------------------------------------------
// Activation
//--------------------------------------------------------------
self.addEventListener('activate', onActivate);
function onActivate(event) {
event.waitUntil(caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key.startsWith(staticCacheNamespace) && key !== staticCacheName) {
return caches.delete(key);
}
}));
}));
}
//--------------------------------------------------------------
// Fetch
//--------------------------------------------------------------
self.addEventListener('fetch', onFetch);
function onFetch(event) {
//Starts with, so variables in the api url can be passed
if (event.request.url.startsWith(apiUrl)) {
//API is online-first with caching
event.respondWith(fetch(event.request).then(function (response) {
//Store the response so the latest version is available when offline
return caches.open(apiCacheName).then(function (cache) {
return cache.put(event.request.url, response.clone()).then(function () {
//Return original response
return response;
});
});
}).catch(function (error) {
//If request cannot be made, return latest cached version
return caches.match(event.request);
}));
} else {
//Static stuff is offline-first
event.respondWith(caches.match(event.request).then(function (response) {
return response || fetch(event.request);
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment