Last active
September 24, 2016 17:43
-
-
Save homam/d1d20daa7e4f53e8224f6dbd2edc7e8d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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