-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
96 lines (87 loc) · 2.59 KB
/
sw.js
File metadata and controls
96 lines (87 loc) · 2.59 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Flow Service Worker
* Network-first for HTML, cache-first for assets
*/
const CACHE_NAME = 'flow-v5';
const STATIC_ASSETS = [
'/flow/',
'/flow/index.html',
'/flow/time.html',
'/flow/offline.html',
'/flow/styles.css',
'/flow/app.js',
'/flow/manifest.json',
'/flow/icon-192.png',
'/flow/icon-512.png'
];
// Install: Cache static assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(STATIC_ASSETS))
.then(() => self.skipWaiting())
);
});
// Activate: Clean up old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(name => name !== CACHE_NAME)
.map(name => caches.delete(name))
);
}).then(() => self.clients.claim())
);
});
// Fetch: Network-first for HTML, cache-first for assets
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
if (!event.request.url.startsWith(self.location.origin)) return;
const isHTML = event.request.mode === 'navigate' ||
event.request.destination === 'document' ||
event.request.url.endsWith('.html');
if (isHTML) {
// Network-first for HTML pages
event.respondWith(
fetch(event.request)
.then(networkResponse => {
if (networkResponse && networkResponse.status === 200) {
const cacheCopy = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, cacheCopy);
});
}
return networkResponse;
})
.catch(() => {
return caches.match(event.request)
.then(cached => cached || caches.match('/flow/offline.html'));
})
);
} else {
// Cache-first for assets
event.respondWith(
caches.match(event.request).then(cachedResponse => {
const fetchPromise = fetch(event.request)
.then(networkResponse => {
if (networkResponse && networkResponse.status === 200) {
const cacheCopy = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, cacheCopy);
});
}
return networkResponse;
})
.catch(() => cachedResponse);
return cachedResponse || fetchPromise;
})
);
}
});
// Handle messages from clients
self.addEventListener('message', (event) => {
if (event.data === 'skipWaiting') {
self.skipWaiting();
}
});