Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

caching only while fetching new records #39

Merged
merged 1 commit into from
Sep 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
})
);
})
);
});
});
Loading