forked from SlyAceZeta/Ribbons.Guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
77 lines (66 loc) · 2.19 KB
/
Copy pathsw.js
File metadata and controls
77 lines (66 loc) · 2.19 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
const APP_CACHE = "app-2026-07-27-0";
const ASSET_CACHE = "assets-v1";
// on installation
self.addEventListener("install", (event) => {
// precache index.html
const requests = ["/", "/index.html", "/PRIVACY.md"].map(
(url) => new Request(url, { cache: "no-cache" })
);
event.waitUntil(
caches.open(APP_CACHE).then((cache) => cache.addAll(requests))
);
});
// on activation
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
// if this is not a current cache, delete it
if(cacheName !== APP_CACHE && cacheName !== ASSET_CACHE){
return caches.delete(cacheName);
}
})
);
})
);
});
// on asset fetch
self.addEventListener("fetch", (event) => {
// ignore requests that aren't fetching an asset (such as POST requests to APIs)
if(event.request.method !== "GET") return;
// parse request URL
const url = new URL(event.request.url);
// bypass cache for local development
if(url.hostname === "127.0.0.1" || url.hostname === "localhost"){
return;
}
// normalize "/" to "/index.html" to avoid duplicating them
const cacheKey = (url.pathname === "/") ? "/index.html" : event.request;
// store images and fonts in a dedicated cache since they rarely change
const isAsset = event.request.destination === "image" || event.request.destination === "font";
const targetCache = isAsset ? ASSET_CACHE : APP_CACHE;
event.respondWith(
caches.match(cacheKey).then((cached) => {
// load everything from cache first if it exists
if(cached) return cached;
// otherwise, fetch from network, cache, and return
return fetch(event.request).then((response) => {
if(response.ok){
const clone = response.clone();
caches.open(targetCache).then(c => c.put(cacheKey, clone));
}
return response;
}).catch(() => {
// if user is offline and this asset isn't cached, fail
return new Response("Asset offline", { status: 503, statusText: "Service Unavailable" });
});
})
);
});
// on message received from app
self.addEventListener("message", (event) => {
if(event.data && event.data.type === "SKIP_WAITING"){
self.skipWaiting();
}
});