Repository navigation
Expand file tree
/
Copy pathservice-worker.js
More file actions
62 lines (57 loc) · 1.79 KB
/
Copy pathservice-worker.js
File metadata and controls
62 lines (57 loc) · 1.79 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
const CACHE_NAME = "securepixel-v2";
const OFFLINE_URL = "/offline.html";
const ASSETS = [
"/",
"/index.html",
"/style.css",
"/script.js",
"/404.html",
OFFLINE_URL, // Add offline page to cache
"https://cdn.tailwindcss.com",
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css",
"https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js",
"https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700&family=Saira:wght@400;500;600;700&display=swap"
];
// Install Event
self.addEventListener("install", (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
// Force the offline page to be cached immediately
return cache.addAll(ASSETS);
})
);
self.skipWaiting();
});
// Activate Event
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) return caches.delete(key);
})
);
})
);
self.clients.claim();
});
// Fetch Event (With Offline Fallback)
self.addEventListener("fetch", (e) => {
// Only handle GET requests
if (e.request.method !== "GET") return;
e.respondWith(
caches.match(e.request)
.then((cachedResponse) => {
// Return cached response if found, else fetch from network
return cachedResponse || fetch(e.request)
.catch(() => {
// If network fails and request is for an HTML page, show offline.html
if (e.request.headers.get("accept").includes("text/html")) {
return caches.match(OFFLINE_URL);
}
});
})
);
});