Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created March 23, 2018 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deanhume/3d662bf675eb70bf4a28f3987bf28935 to your computer and use it in GitHub Desktop.
Save deanhume/3d662bf675eb70bf4a28f3987bf28935 to your computer and use it in GitHub Desktop.
Service Worker for Ghost CMS
const cacheName = 'blogCache';
const offlineUrl = '/offline/';
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll([
'./assets/font/icons.woff2',
'./assets/js/script.js',
'https://fonts.googleapis.com/css?family=Open+Sans:400,700',
offlineUrl
]))
);
});
// Cache any new resources as they are fetched
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function (response) {
if (!response || response.status !== 200) {
return response;
}
var responseToCache = response.clone();
caches.open(cacheName)
.then(function (cache) {
cache.put(event.request, responseToCache);
});
return response;
}
).catch(error => {
// Check if the user is offline first and is trying to navigate to a web page
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
// Return the offline page
return caches.match(offlineUrl);
}
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment