-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
caching only while fetching new records (#39)
Co-authored-by: Gokul K <gokulk@Gokuls-MacBook-Air.local>
- Loading branch information
Showing
1 changed file
with
41 additions
and
21 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
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); | ||
} | ||
}) | ||
); | ||
}) | ||
); | ||
}); | ||
}); |