-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Set up SWR service worker when the app is installed
- Loading branch information
1 parent
40b17a0
commit f06e36a
Showing
5 changed files
with
136 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
const CACHE_NAME = 'my-csr-app' | ||
const CACHED_URLS = ['/', ...self.__WB_MANIFEST.map(({ url }) => url)] | ||
const MAX_STALE_DURATION = 7 * 24 * 60 * 60 | ||
|
||
const preCache = async () => { | ||
await caches.delete(CACHE_NAME) | ||
|
||
const cache = await caches.open(CACHE_NAME) | ||
|
||
await cache.addAll(CACHED_URLS) | ||
} | ||
|
||
const staleWhileRevalidate = async request => { | ||
const documentRequest = request.destination === 'document' | ||
|
||
if (documentRequest) request = new Request(self.registration.scope) | ||
|
||
const cache = await caches.open(CACHE_NAME) | ||
const cachedResponsePromise = await cache.match(request) | ||
const networkResponsePromise = fetch(request) | ||
|
||
if (documentRequest) { | ||
networkResponsePromise.then(response => cache.put(request, response.clone())) | ||
|
||
if ((new Date() - new Date(cachedResponsePromise?.headers.get('date'))) / 1000 > MAX_STALE_DURATION) { | ||
return networkResponsePromise | ||
} | ||
|
||
return cachedResponsePromise | ||
} | ||
|
||
return cachedResponsePromise || networkResponsePromise | ||
} | ||
|
||
self.addEventListener('install', event => { | ||
event.waitUntil(preCache()) | ||
self.skipWaiting() | ||
}) | ||
|
||
self.addEventListener('fetch', event => { | ||
if (['document', 'font', 'script'].includes(event.request.destination)) { | ||
event.respondWith(staleWhileRevalidate(event.request)) | ||
} | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters