Skip to content

Commit

Permalink
caching only while fetching new records (#39)
Browse files Browse the repository at this point in the history
Co-authored-by: Gokul K <gokulk@Gokuls-MacBook-Air.local>
  • Loading branch information
gokulk16 and Gokul K committed Sep 22, 2024
1 parent 8918dc5 commit c670cbf
Showing 1 changed file with 41 additions and 21 deletions.
62 changes: 41 additions & 21 deletions sw.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
// sw.js
const CACHE_NAME = "ttc-cache-v1";
const urlsToCache = [
"/",
"/index.html",
"/css/*.css",
"/js/editor.js",
"/favicon-150.png",
"/favicon-48.png",
"/favicon-512.png",
"/favicon-192.png",
];

// Install the service worker
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
// Fetch event: Cache responses immediately after fetching
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
// If a match is found in the cache, return it; otherwise, fetch from network
return (
cachedResponse ||
fetch(event.request).then((networkResponse) => {
// Check if we received a valid response
if (
!networkResponse ||
networkResponse.status !== 200 ||
networkResponse.type !== "basic"
) {
return networkResponse; // Return the response if it's not valid for caching
}

// Clone the response because we can only use it once
const responseToCache = networkResponse.clone();

// Open the cache and store the response
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});

return networkResponse; // Return the original network response
})
);
})
);
});

// Fetch the cached assets
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
// Activate event: Clean up old caches if necessary
self.addEventListener("activate", (event) => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
});

0 comments on commit c670cbf

Please sign in to comment.