-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
87 lines (79 loc) · 2.92 KB
/
Copy pathsw.js
File metadata and controls
87 lines (79 loc) · 2.92 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
var CACHE = 'weathervue-v2';
var STATIC_ASSETS = [
'/',
'/index.html',
'/script.js',
'/manifest.json',
'/icons/icon-192.svg',
'/icons/icon-512.svg',
'/icons/favicon.svg',
];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE).then(function (cache) {
return Promise.allSettled(STATIC_ASSETS.map(function (url) {
return cache.add(url).catch(function () {});
}));
})
);
self.skipWaiting();
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keys) {
return Promise.all(
keys.filter(function (k) { return k !== CACHE; }).map(function (k) { return caches.delete(k); })
);
}).then(function () {
return self.clients.claim();
})
);
});
function shouldCache(url) {
var path = url.pathname;
if (path.indexOf('/api/') === 0) return true;
if (path === '/' || path === '/index.html' || path === '/script.js') return true;
if (path.indexOf('/icons/') === 0) return true;
return false;
}
self.addEventListener('fetch', function (event) {
var url = new URL(event.request.url);
// Only intercept same-origin requests (skip map tiles, weather icons, etc.)
if (url.origin !== self.location.origin) return;
var isApi = url.pathname.indexOf('/api/') === 0;
// API calls: network first, cache fallback, notify client
if (isApi) {
event.respondWith(
fetch(event.request).then(function (resp) {
var clone = resp.clone();
caches.open(CACHE).then(function (cache) { cache.put(event.request, clone); });
return resp;
}).catch(function () {
return caches.match(event.request).then(function (cached) {
if (cached) {
self.clients.matchAll().then(function (clients) {
clients.forEach(function (c) { c.postMessage({ type: 'offline', url: url.pathname }); });
});
}
return cached || new Response(JSON.stringify({ error: 'Offline' }), {
status: 503, headers: { 'Content-Type': 'application/json' },
});
});
})
);
return;
}
// Static assets: cache first, network fallback
event.respondWith(
caches.match(event.request).then(function (cached) {
var fetchPromise = fetch(event.request).then(function (resp) {
if (shouldCache(url)) {
var clone = resp.clone();
caches.open(CACHE).then(function (cache) { cache.put(event.request, clone); });
}
return resp;
}).catch(function () { return cached; });
return cached || fetchPromise;
})
);
});