Reputation: 8656
Hello all I am having the following code to load the page on offline, I have a requirement where I need to cache few pages and exclude few from cache. The code I wrote is working fine but when ever I push any updates to the site it is loading from cache how to reload it from server instead of cache when online
I referred to this blog and sum up with some modifications
https://www.charistheo.io/blog/2021/03/cache-handling-with-service-workers-and-the-cache-api/
self.addEventListener("install", function (e) {
self.skipWaiting();
e.waitUntil(async function () {
const cache = await caches.open("app");
await cache.addAll([
"/Scripts/jquery-3.6.0.min.js",
"/ReportableEvent/Index",
"/NearMissReport/Index",
"/ReportableEvent/InternalReview?ReportableEventId=0"
)];
}());
});
var uncachedPaths = new Set(["/Reportable/Reports", "/Dashboard/Index"]);
self.addEventListener("fetch", async function (e) {
if (e.request.method !== "GET") {
return;
}
e.respondWith(
caches.match(e.request, { ignoreSearch: true }).then(async cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
else {
if (e.request.url.includes("service-worker.js") && !navigator.onLine) {
return;
}
// Fetch the requested resource from the network if it does not exist in the cache.
const networkResponse = await fetch(e.request);
// Response needs to be cloned if going to be used more than once.
const clonedResponse = networkResponse.clone();
if (!uncachedPaths.has(new URL(e.request.url).pathname)) {
// Save response to runtime cache for later use.
const runtimeCache = await caches.open("app");
runtimeCache.put(e.request, networkResponse);
}
// Respond with the cloned network response.
return Promise.resolve(clonedResponse);
}
})
);
});
Also is this correct to cache the page which has Query strings "/ReportableEvent/InternalReview?ReportableEventId=0"
Upvotes: 0
Views: 1880
Reputation: 637
There are various approaches how to serve files from cache and how to update/invalidate the cache. please, refer here.
Also, if you are updating your service worker js files and want to update the cache as well, try appending version to cache name. For instance,
var version = 1.0;
var cachename= 'app'+version;
And every time you update the file, you can increment the version. This way every updates makes it new cache and files are stored afresh in cache.
Upvotes: 1