Skip to content

Instantly share code, notes, and snippets.

@nilesolutions
Forked from jarodium/sw.js
Created February 14, 2020 19:53
Show Gist options
  • Save nilesolutions/579ed1c84cb184ac8e294bc1a4ed8a7f to your computer and use it in GitHub Desktop.
Save nilesolutions/579ed1c84cb184ac8e294bc1a4ed8a7f to your computer and use it in GitHub Desktop.
Service Worker
'use strict';
var cacheVersion = 1;
var currentCache = {
offline: 'offline-cache' + cacheVersion
};
const offlineUrl = 'offline.html';
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache.offline).then(function(cache) {
return cache.addAll([
'./img/logo-4t1-invert.png',
offlineUrl
]);
})
);
});
this.addEventListener('fetch', event => {
// request.mode = navigate isn't supported in all browsers
// so include a check for Accept: text/html header.
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match(offlineUrl);
})
);
}
else{
// Respond with everything else if we can
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment