Skip to content

Commit c670cbf

Browse files
gokulk16Gokul K
and
Gokul K
authored
caching only while fetching new records (#39)
Co-authored-by: Gokul K <[email protected]>
1 parent 8918dc5 commit c670cbf

File tree

1 file changed

+41
-21
lines changed

1 file changed

+41
-21
lines changed

sw.js

+41-21
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,50 @@
11
// sw.js
22
const CACHE_NAME = "ttc-cache-v1";
3-
const urlsToCache = [
4-
"/",
5-
"/index.html",
6-
"/css/*.css",
7-
"/js/editor.js",
8-
"/favicon-150.png",
9-
"/favicon-48.png",
10-
"/favicon-512.png",
11-
"/favicon-192.png",
12-
];
133

14-
// Install the service worker
15-
self.addEventListener("install", (event) => {
16-
event.waitUntil(
17-
caches.open(CACHE_NAME).then((cache) => {
18-
return cache.addAll(urlsToCache);
4+
// Fetch event: Cache responses immediately after fetching
5+
self.addEventListener("fetch", (event) => {
6+
event.respondWith(
7+
caches.match(event.request).then((cachedResponse) => {
8+
// If a match is found in the cache, return it; otherwise, fetch from network
9+
return (
10+
cachedResponse ||
11+
fetch(event.request).then((networkResponse) => {
12+
// Check if we received a valid response
13+
if (
14+
!networkResponse ||
15+
networkResponse.status !== 200 ||
16+
networkResponse.type !== "basic"
17+
) {
18+
return networkResponse; // Return the response if it's not valid for caching
19+
}
20+
21+
// Clone the response because we can only use it once
22+
const responseToCache = networkResponse.clone();
23+
24+
// Open the cache and store the response
25+
caches.open(CACHE_NAME).then((cache) => {
26+
cache.put(event.request, responseToCache);
27+
});
28+
29+
return networkResponse; // Return the original network response
30+
})
31+
);
1932
})
2033
);
2134
});
2235

23-
// Fetch the cached assets
24-
self.addEventListener("fetch", (event) => {
25-
event.respondWith(
26-
caches.match(event.request).then((response) => {
27-
return response || fetch(event.request);
36+
// Activate event: Clean up old caches if necessary
37+
self.addEventListener("activate", (event) => {
38+
const cacheWhitelist = [CACHE_NAME];
39+
event.waitUntil(
40+
caches.keys().then((cacheNames) => {
41+
return Promise.all(
42+
cacheNames.map((cacheName) => {
43+
if (cacheWhitelist.indexOf(cacheName) === -1) {
44+
return caches.delete(cacheName);
45+
}
46+
})
47+
);
2848
})
2949
);
30-
});
50+
});

0 commit comments

Comments
 (0)