Skip to content

Commit a8ef717

Browse files
committed
feat: Enhance service worker caching to fallback on network failures or non-200 responses, fix cache size limiting recursion, and enable updates on page load.
1 parent d8b352d commit a8ef717

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ if ('serviceWorker' in navigator) {
7979
.register('./sw.js')
8080
.then((registration) => {
8181
console.log('SW registered: ', registration);
82+
// Check for updates on every page load
83+
registration.update();
8284
})
8385
.catch((registrationError) => {
8486
console.log('SW registration failed: ', registrationError);

public/sw.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const limitCacheSize = (name, maxItems) => {
1010
caches.open(name).then((cache) => {
1111
cache.keys().then((keys) => {
1212
if (keys.length > maxItems) {
13-
cache.delete(keys[0]).then(limitCacheSize(name, maxItems));
13+
cache.delete(keys[0]).then(() => limitCacheSize(name, maxItems));
1414
}
1515
});
1616
});
@@ -69,16 +69,20 @@ self.addEventListener('fetch', (event) => {
6969
event.respondWith(
7070
fetch(event.request)
7171
.then((networkResponse) => {
72+
// If network is ok, cache and return
7273
if (networkResponse && networkResponse.status === 200) {
7374
const responseToCache = networkResponse.clone();
7475
caches.open(CACHE_NAME).then((cache) => {
7576
cache.put(event.request, responseToCache);
7677
limitCacheSize(CACHE_NAME, MAX_CACHE_ITEMS);
7778
});
79+
return networkResponse;
7880
}
79-
return networkResponse;
81+
// If status is not 200, try cache
82+
return caches.match(event.request).then((cached) => cached || networkResponse);
8083
})
8184
.catch(() => {
85+
// If fetch fails (offline), try cache
8286
return caches.match(event.request);
8387
})
8488
);

0 commit comments

Comments
 (0)