-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
80 lines (71 loc) · 2.13 KB
/
sw.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
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
// servie worker
const cache_Name = "pwa-imageoptimizer-v1.0.04";
const staticAssets = [
'/',
'/index.html',
'/features.html',
'/contactus.html',
'/privacy.html',
];
// handle service worker install
self.addEventListener('install', function (event) {
event.waitUntil(
caches
.open(cache_Name).then(function (cache) {
return cache.addAll(staticAssets);
})
.then(() => {
self.skipWaiting();
})
);
});;
// handle fetch requests
self.addEventListener('fetch', async event => {
const req = event.request;
if (/.*(json)$/.test(req.url)) {
event.respondWith(networkFirst(req));
} else {
event.respondWith(cacheFirst(req));
}
});
async function cacheFirst(req) {
const cache = await caches.open(cache_Name);
const cachedResponse = await cache.match(req);
return cachedResponse || networkFirst(req);
}
async function networkFirst(req) {
const cache = await caches.open(cache_Name);
try {
const fresh = await fetch(req);
cache.put(req, fresh.clone());
return fresh;
} catch (e) {
// const cachedResponse = await cache.match(req);
return caches.match('/offline.html');
}
}
// handle old cache remove
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.filter(function (cacheName) {
return true;
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function (cacheName) {
if (cache_Name != cacheName && cacheName.startsWith("pwa-imageoptimizer")) {
return caches.delete(cacheName);
}
})
);
})
);
});
// handle message for refresh
self.addEventListener('message', function (event) {
if (event.data.action === 'skipWaiting') {
self.skipWaiting();
}
});