-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
56 lines (52 loc) · 1.53 KB
/
sw.js
File metadata and controls
56 lines (52 loc) · 1.53 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
// Files To Cache
const version = '1.11'; // Added Dew Point - Considered feature complete
const cName = `Weather-v${version}`; // Ensures that with updated service workers, the old cache is not reused, and a new cache is created.
const cFiles = [
"index.html",
"style.css",
"pulltorefresh.js",
"main.js",
// "offline.html" // Optional: Add an offline fallback page
];
// Create/Install Cache
self.addEventListener("install", (evt) => {
evt.waitUntil(
caches.open(cName)
.then((cache) => cache.addAll(cFiles))
.catch((err) => console.error("Failed to cache resources:", err))
);
});
// Clean Up Old Caches
self.addEventListener("activate", (evt) => {
evt.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== cName)
.map((name) => caches.delete(name))
);
})
);
});
// Fetch Strategy: Network First, Fallback To Cache
self.addEventListener("fetch", (evt) => {
evt.respondWith(
fetch(evt.request)
.catch(() => {
return caches.match(evt.request)
.then((res) => res || new Response("Offline and no cached response available", { status: 503 }));
})
);
});
// Clean Up Old Caches
self.addEventListener("activate", (evt) => {
evt.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== cName)
.map((name) => caches.delete(name))
);
})
);
});