-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsw.js
More file actions
56 lines (51 loc) · 2.01 KB
/
Copy pathsw.js
File metadata and controls
56 lines (51 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const CACHE_NAME = 'flowapp-dynamic-cache-v1';
const STATIC_ASSETS = [
'./',
'./index.html',
'./index.js',
'./manifest.json',
'https://raw.githubusercontent.com/google/generative-ai-docs/main/site/en/gemma/images/gemma_logo.png'
];
// On install, pre-cache the static shell
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(STATIC_ASSETS))
.then(() => self.skipWaiting()) // Activate new SW immediately
);
});
// On activate, clean up old caches
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName.startsWith('flowapp-') && cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
}).then(() => self.clients.claim())
);
});
// Use "Stale-While-Revalidate" strategy for all requests
self.addEventListener('fetch', event => {
event.respondWith(
caches.open(CACHE_NAME).then(cache => {
return cache.match(event.request).then(cachedResponse => {
const fetchPromise = fetch(event.request).then(networkResponse => {
// If we got a valid response, update the cache
if (networkResponse && networkResponse.status === 200) {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
}).catch(err => {
// fetch failed, probably offline, do nothing.
console.warn(`Fetch failed for ${event.request.url}; returning cached response instead.`, err);
});
// Return the cached response immediately, and update the cache in the background.
return cachedResponse || fetchPromise;
});
})
);
});