-
Notifications
You must be signed in to change notification settings - Fork 4
/
service-worker.js
44 lines (41 loc) · 1.11 KB
/
service-worker.js
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
const CACHE_NAME = 'offline-cache-v2.0.9';
const urlsToCache = [
'/',
'/index.html',
'/ico.png',
'/manifest.json',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function (event) {
const cacheWhitelist = [CACHE_NAME]; // 只保留当前的缓存
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName); // 删除过时的缓存
}
})
);
})
);
self.clients.claim();
});
self.addEventListener('fetch', function (event) {
const requestUrl = new URL(event.request.url);
if (/\.(html|css|js|png|jpg|jpeg|gif|svg)$/.test(requestUrl.pathname)) {
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
} else {
event.respondWith(fetch(event.request));
}
});