Skip to content

Commit

Permalink
Fix sw cache (#345)
Browse files Browse the repository at this point in the history
* Fix sw cache

* Fix sw cache

* Fix sw cache
  • Loading branch information
sonic16x authored Nov 23, 2024
1 parent 39f229c commit 654aa12
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "interslavic",
"version": "1.24.1",
"version": "1.24.2",
"description": "Interslavic Dictionary",
"license": "MIT",
"author": {
Expand Down
39 changes: 26 additions & 13 deletions src/serviceWorker/sw.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { CASH_URLS } from './cashUrls';

// Add to cache all data
self.addEventListener("install", (event: any) => {
event.waitUntil(
caches
.open(`${VERSION}fundamentals`)
.open(VERSION)
.then((cache) => cache.addAll(CASH_URLS))
);
});
Expand All @@ -13,33 +14,45 @@ self.addEventListener("fetch", (event: any) => {
return;
}

// Try to find data in cache
event.respondWith(
caches
.match(event.request)
.then((cached) => {
const networked = fetch(event.request)
.then((response: any) => {
const cacheCopy = response.clone();

.then((cache) => {
// Request data from network
const network = fetch(event.request)
.then((response) => (
caches
.open(`${VERSION}pages`)
.then((cache) => cache.put(event.request, cacheCopy))

return response;
});
.open(VERSION)
.then((cache) => cache.put(event.request, response.clone())) // Update cache
.then(() => response)
));

return cached || networked;
// Prefer get data from cache here
return cache || network;
})
);

// Update cache in background
event.waitUntil(
caches
.open(VERSION)
.then((cache) => (
fetch(event.request).then((response) =>
cache.put(event.request, response.clone())
)
))
);
});

self.addEventListener("activate", (event: any) => {
// Delete old cache versions
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(
keys
.filter((key) => !key.startsWith(VERSION))
.filter((key) => key !== VERSION)
.map((key) => caches.delete(key))
))
);
Expand Down

0 comments on commit 654aa12

Please sign in to comment.