Skip to content

Commit

Permalink
fix [PWA]: clear old caches versions
Browse files Browse the repository at this point in the history
  • Loading branch information
Moamal-2000 committed Dec 14, 2024
1 parent 033506a commit 38042a4
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";

// Variables
const CACHE_NAME = "e-commerce-v8";
const CACHE_NAME = "e-commerce-v9";
const ASSETS = [
"/",
"/index.html",
Expand All @@ -18,6 +18,8 @@ const ASSETS = [
async function cacheAssets() {
const cache = await caches.open(CACHE_NAME);
await cache.addAll(ASSETS);

clearOldCaches();
}

async function handleFetchAndCache(request) {
Expand Down Expand Up @@ -59,32 +61,31 @@ async function updateCachedAssets() {
})
);

const cacheKeys = await caches.keys();
await Promise.all(
cacheKeys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
);

return responses;
} catch (error) {
console.error("Failed to update cache:", error);
}
}

function handleFetchEvent(event) {
const isGetMethod = event.request.method === "GET";

event.respondWith(handleFetchAndCache(event.request));
async function clearOldCaches() {
const cacheKeys = await caches.keys();

if (isGetMethod) {
event.waitUntil(updateCachedAssets());
}
await Promise.all(
cacheKeys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
);
}

// Events
self.addEventListener("install", (event) => event.waitUntil(cacheAssets()));
self.addEventListener("activate", (event) =>
event.waitUntil(updateCachedAssets())
);
self.addEventListener("fetch", handleFetchEvent);
self.addEventListener("install", (event) => {
event.waitUntil(cacheAssets());
});

self.addEventListener("activate", (event) => {
event.waitUntil(updateCachedAssets());
});

self.addEventListener("fetch", (event) => {
event.respondWith(handleFetchAndCache(event.request));
});

0 comments on commit 38042a4

Please sign in to comment.