Created
March 23, 2018 16:46
-
-
Save deanhume/3d662bf675eb70bf4a28f3987bf28935 to your computer and use it in GitHub Desktop.
Service Worker for Ghost CMS
This file contains hidden or 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 = '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