Skip to content

Instantly share code, notes, and snippets.

@kimhogeling
Created July 28, 2016 13:05
Show Gist options
  • Save kimhogeling/5403baa13c11a0f8f068b01ab462d570 to your computer and use it in GitHub Desktop.
Save kimhogeling/5403baa13c11a0f8f068b01ab462d570 to your computer and use it in GitHub Desktop.
Service Worker of the shopping24 hacking days wohnklamotte prototype
/**
* KH: Warning! This is part of a prototype made during our early 2016 hacking days and is not suitable for production!
*/
const VERSION = 's24-wokl-social-v6'
const CACHE_FILES = [
'/',
'/index.html',
'/public/css/card.css',
'/public/css/header.css',
'/public/css/mainSection.css',
'/public/css/refreshButton.css',
'/public/img/icon.png',
'/public/img/logo.png',
'/public/img/twitter.png',
'/public/img/facebook.png',
'/public/img/instagram.png',
'/public/js/app.js',
'/manifest.json'
]
self.addEventListener('install', event => {
console.log('Installing ServiceWorker with version: ', VERSION)
event.waitUntil(
caches.open(VERSION)
.then(cache => cache.addAll(CACHE_FILES))
)
})
self.addEventListener('activate', event => {
console.log('ServiceWorker got activated.')
event.waitUntil(
caches.keys()
.then(keylist =>
Promise.all(
keylist.map(key => {
if (key.startsWith('s24-wokl-social-') && (key !== VERSION)) {
console.log('Delete Cache: ', key)
return caches.delete(key)
}
})
)
)
)
})
self.addEventListener('fetch', event => {
// will be overwritten if a match is found in cache
let response
// do not try to read third party urls from cache
if (!event.request.url.startsWith('http://localhost')) {
return fetch(event.request)
}
event.respondWith(
// try to respond cached assets
caches.match(event.request)
.then(r => {
response = r
// KH: "I don't understand this,
// before returning the cached asset, put it into cache?"
caches.open(VERSION).then(cache => {
cache.put(event.request, response)
})
// return the cached asset
return response.clone()
})
// if something goes wrong, simply fetch the original request
.catch(err => fetch(event.request))
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment