-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsw.js
More file actions
80 lines (72 loc) Β· 2.61 KB
/
sw.js
File metadata and controls
80 lines (72 loc) Β· 2.61 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
/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Spin Web - Service Worker
Offline-first caching for PWA / iOS Home Screen
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
var CACHE_NAME = 'spin-web-v2';
var ASSETS = [
'./',
'./index.html',
'./style.css',
'./app.js',
'./icon.svg',
'./manifest.json'
];
/* βββ Install: pre-cache shell assets βββββββββββββββββββ */
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(ASSETS);
}).then(function() {
return self.skipWaiting();
})
);
});
/* βββ Activate: clean old caches ββββββββββββββββββββββββ */
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(
keys.filter(function(key) {
return key !== CACHE_NAME;
}).map(function(key) {
return caches.delete(key);
})
);
}).then(function() {
return self.clients.claim();
})
);
});
/* βββ Fetch: cache-first for app shell, network-first for others ββ */
self.addEventListener('fetch', function(event) {
var url = new URL(event.request.url);
// Only handle same-origin requests
if (url.origin !== location.origin) return;
// Cache-first for known assets
event.respondWith(
caches.match(event.request).then(function(cached) {
if (cached) {
// Return cached version immediately, update cache in background
fetch(event.request).then(function(response) {
if (response && response.status === 200) {
var responseClone = response.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
}
}).catch(function() { /* offline, skip background update */ });
return cached;
}
// Not cached: fetch from network, cache if successful
return fetch(event.request).then(function(response) {
if (response && response.status === 200) {
var responseClone = response.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
}
return response;
});
})
);
});