Better caching in service worker
This commit is contained in:
parent
d9f123cb08
commit
c1a6f6f515
@ -1,10 +1,11 @@
|
||||
self.addEventListener('install', function (event) {
|
||||
console.log('Service Worker installing.', event);
|
||||
caches.open('v1').then(function (cache) {
|
||||
return cache.addAll([
|
||||
'offline.html',
|
||||
]);
|
||||
});
|
||||
event.waitUntil(
|
||||
caches.open('v1').then(function (cache) {
|
||||
return cache.addAll([
|
||||
'offline.html',
|
||||
]);
|
||||
}))
|
||||
});
|
||||
|
||||
self.addEventListener('activate', function (event) {
|
||||
@ -22,19 +23,34 @@ self.addEventListener('push', /** @param {PushEvent} event */ function (event) {
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', /** @param {FetchEvent} event */ async function (event) {
|
||||
console.log('Service Worker fetching.', event);
|
||||
console.log('Service Worker fetching.', event, event.request.url);
|
||||
|
||||
const cache = await caches.open('v1');
|
||||
const cachedResponse = await cache.match(event.request);
|
||||
async function staleWhileRevalidate() {
|
||||
const cache = await caches.open('v1');
|
||||
|
||||
const fetchedResponse = fetch(event.request)
|
||||
.then(function (networkResponse) {
|
||||
cache.put(event.request, networkResponse.clone());
|
||||
return networkResponse;
|
||||
})
|
||||
.catch(function () {
|
||||
return cache.match('offline.html');
|
||||
});
|
||||
const fetchedResponse = fetch(event.request)
|
||||
.then(function (networkResponse) {
|
||||
if (networkResponse.ok) {
|
||||
cache.put(event.request, networkResponse.clone());
|
||||
}
|
||||
return networkResponse;
|
||||
})
|
||||
.catch(async function () {
|
||||
const offline = await cache.match('offline.html');
|
||||
return offline || Response.error();
|
||||
});
|
||||
|
||||
event.respondWith(cachedResponse || fetchedResponse);
|
||||
return (await cache.match(event.request)) || (await fetchedResponse);
|
||||
}
|
||||
|
||||
function isCacheable(url) {
|
||||
const pathname = new URL(url).pathname;
|
||||
return !pathname.startsWith('login')
|
||||
}
|
||||
|
||||
if (event.request.method === 'GET' && isCacheable(event.request.url)) {
|
||||
console.log('interceptiing fetch', event.request.url);
|
||||
return event.respondWith(staleWhileRevalidate());
|
||||
}
|
||||
// fall back to default behaviour
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user