Skip to content

Commit

Permalink
Add a max stale duration parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
theninthsky committed Nov 29, 2022
1 parent 6a40fd0 commit 17dfd5e
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions public/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const CACHE_NAME = 'client-side-rendering'
const CACHED_URLS = ['/', ...self.__WB_MANIFEST.map(({ url }) => url)]
const MAX_STALE_DURATION = 60

const preCache = async () => {
await caches.delete(CACHE_NAME)
Expand All @@ -10,23 +11,23 @@ const preCache = async () => {
}

const staleWhileRevalidate = async request => {
const rootDocumentRequest = new Request(self.registration.scope)

if (request.destination === 'document') request = rootDocumentRequest
if (request.destination === 'document') request = new Request(self.registration.scope)

const cache = await caches.open(CACHE_NAME)
const cachedResponsePromise = await cache.match(request)
const networkResponsePromise = fetch(request)

if (cachedResponsePromise || request.destination === 'document') {
if (request.destination === 'document') {
networkResponsePromise.then(response => cache.put(request, response.clone()))
if (request.destination === 'document') {
networkResponsePromise.then(response => cache.put(request, response.clone()))

if (new Date() - new Date(cachedResponsePromise?.headers.get('date')) > MAX_STALE_DURATION) {
return networkResponsePromise
}

return cachedResponsePromise || networkResponsePromise
return cachedResponsePromise
}

return networkResponsePromise
return cachedResponsePromise || networkResponsePromise
}

self.addEventListener('install', event => {
Expand Down

0 comments on commit 17dfd5e

Please sign in to comment.