Skip to content

Instantly share code, notes, and snippets.

@homam
Last active September 24, 2016 17:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save homam/d1d20daa7e4f53e8224f6dbd2edc7e8d to your computer and use it in GitHub Desktop.
Save homam/d1d20daa7e4f53e8224f6dbd2edc7e8d to your computer and use it in GitHub Desktop.
const cacheName = 'my-cache-1'
self.addEventListener('install', event => {
console.log('install')
});
self.addEventListener('activate', event => {
console.log('activate')
event.waitUntil(self.clients.claim())
});
const cachedFetch = request => request.method != 'GET' ?
// we can only cache GET requests
fetch(request) :
caches.open(cacheName).then(cache =>
cache.match(request).then(resp => {
if(!!resp) {
console.log('from cache', request.url)
return resp;
} else {
console.log('not in cache', request.url)
return fetch(request).then(response => {
// put the new response in the cache for next fetches
cache.put(request, response.clone());
return response
})
}
})
)
self.addEventListener('fetch', event => event.respondWith(
cachedFetch(event.request)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment