Instantly share code, notes, and snippets.

Embed
What would you like to do?
var cacheVersion = 'v1';
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(cacheVersion)
.then(function (cache) {
return cache.addAll([
'/offline',
'https://mycdn.com/style.css',
'https://mycdn.com/script.js',
'https://mycdn.com/img/logo.svg',
'https://mycdn.com/img/offline.png'
]);
});
}
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches whose name is no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(cacheVersion) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET') {
event.respondWith(
fetch(request, { credentials: 'include' })
);
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(
fetch(request, { credentials: 'include' })
.then(function (response) {
// Stash a copy of this page in the cache
var copy = response.clone();
caches.open(cacheVersion)
.then(function (cache) {
cache.put(request, copy);
});
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
if (self.clients) {
clients.matchAll()
.then(function(clients) {
// wait until fallback site is loaded
setTimeout(function(){
for (var client of clients) {
client.postMessage('offline');
}
}, 500);
});
}
return response || caches.match('/offline');
});
})
);
return;
}
// For non-HTML requests, look in the cache first, fall back to the network
event.respondWith(
caches.match(request)
.then(function (response) {
return response || fetch(request)
.catch(function () {
// If the request is for an image, show an offline placeholder
if (request.headers.get('Accept').indexOf('image') !== -1) {
return caches.match('https://mycdn.com/img/offline.png');
}
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment