Skip to content

Instantly share code, notes, and snippets.

@lgescobar
Last active April 8, 2018 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgescobar/be561df693fbdc8051a1bd73c2cf2473 to your computer and use it in GitHub Desktop.
Save lgescobar/be561df693fbdc8051a1bd73c2cf2473 to your computer and use it in GitHub Desktop.
Basic service worker to cache only selected paths from the installed domain and serve them from cache in case of server error.
let version = 1;
let cacheName = self.location.hostname + version;
let allowedPaths = [
/^\/(\?utm_source=homescreen)?$/,
// Also matches /article/news/... !!
/\/news\/?.*$/
];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll([
'/',
'/?utm_source=homescreen'
]);
})
);
});
self.addEventListener('activate', (e) => {
if (self.clients && clients.claim) {
clients.claim();
}
});
self.addEventListener('fetch', (e) => {
const requestUrl = new URL(e.request.url);
if (requestUrl.hostname === self.location.hostname
&& allowedPaths.some((allowedExp) => allowedExp.test(requestUrl.pathname))
) {
e.respondWith(
fetch(e.request).then((res) => {
if (res.status >= 500) {
return caches.match(e.request)
} else {
return caches.open(cacheName).then((cache) => {
cache.put(e.request, res.clone());
return res;
});
}
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment