Skip to content

Commit

Permalink
service_worker_update (#379)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lungsangg authored Oct 8, 2024
2 parents 04e8954 + 30d700e commit 17a1394
Showing 1 changed file with 52 additions and 35 deletions.
87 changes: 52 additions & 35 deletions static/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,62 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');

// Define your cache name
const CACHE = "pwabuilder-page";

// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "ToDo-replace-this-name.html";
// Replace this with the actual offline page
const offlineFallbackPage = "/";

// Workbox Precache and Routing
workbox.precaching.precacheAndRoute([
{ url: '/', revision: '1' },
{ url: '/index.html', revision: '1' },
{ url: '/styles.css', revision: '1' },
{ url: '/script.js', revision: '1' },
{ url: '/icon.png', revision: '1' },
{ url: `/${offlineFallbackPage}`, revision: '1' }
]);

// Fallback for offline page
self.addEventListener('install', async event => {
event.waitUntil(
caches.open(CACHE).then(function (cache) {
return cache.addAll([
offlineFallbackPage,
'/index.html',
'/styles.css',
'/script.js',
'/icon.png'
]);
})
);
self.skipWaiting();
});

self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
// Fetch event to serve from cache or fallback to network
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
return cachedResponse || fetch(event.request).catch(() => {
// If both fail, show the offline fallback page
return caches.match(offlineFallbackPage);
});
})
);
});

self.addEventListener('install', async (event) => {
// Activate the new service worker and clean up old caches
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE];
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
caches.keys().then(keyList =>
Promise.all(
keyList.map(key => {
if (!cacheWhitelist.includes(key)) {
return caches.delete(key);
}
})
)
)
);
self.clients.claim();
});

if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}

self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;

if (preloadResp) {
return preloadResp;
}

const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {

const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});

0 comments on commit 17a1394

Please sign in to comment.