Skip to content

Instantly share code, notes, and snippets.

@luke-denton-aligent
Created November 16, 2016 05:46
Show Gist options
  • Save luke-denton-aligent/8bbe12dc6d05ad457558b64da2d2fa62 to your computer and use it in GitHub Desktop.
Save luke-denton-aligent/8bbe12dc6d05ad457558b64da2d2fa62 to your computer and use it in GitHub Desktop.
This snippet shows how to cache images and serve them from the cache, if available
var contentImgsCache = 'my-content-imgs'; //Set up the name of the cache for the images. This will be different to the normal cache, as images will likely be persisted for longer
self.addEventListener('fetch', function(event) {
var requestUrl = new URL(event.request.url);
//See previous snippets for explanation of this
if (requestUrl.origin === location.origin) {
if (requestUrl.pathname.startsWith('/photos/')) {
event.respondWith(servePhoto(event.request));
return;
}
}
//Handle response if this request isn't for a photo
});
//Serve a photo to the browser, checking for it in the cache first, and if not found there, making a network request to get it, and then store it in the cache
function servePhoto(request) {
var storageUrl = request.url.replace(/-\d+px\.jpg$/, '');
return caches.open(contentImgsCache).then(function(cache) {
return cache.match(stroageUrl).then(function(){
if (response) return response;
return fetch(response).then(function(networkResponse){
cache.put(stroageUrl, networkResponse.clone()); //Need to clone the response as it can only be used once
return networkResponse;
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment