-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsw.js
81 lines (68 loc) · 2.27 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
// Choose a cache name
const version = 16;
const cacheName = 'cache-v' + version;
// List the files to precache
const precacheResources = [
'/',
'/index.html',
'/script.js',
'/style.css',
'/OpenSans-Regular.woff',
'/favicon.ico',
'/manifest.json',
'/icon-192.png',
'/icon-512-maskable.png',
'/back.svg',
'https://unpkg.com/[email protected]/lib/browser/math.js',
];
addEventListener("install", (event) => {
const preCache = async () => {
const cache = await caches.open(cacheName);
console.log(precacheResources);
return cache.addAll(precacheResources);
};
event.waitUntil(preCache());
});
self.addEventListener('activate', (event) => {
console.log('Service worker activate event!');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.filter((name) => name !== cacheName)
.map((name) => caches.delete(name))
);
})
);
});
self.addEventListener('fetch', (event) => {
// Ignore requests to Google Analytics and Google Tag Manager
if (event.request.url.includes('google-analytics.com') || event.request.url.includes('googletagmanager.com')) {
return;
}
console.log('Fetch intercepted for:', event.request.url);
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
// If the requested resource is in the cache, return it
if (cachedResponse) {
console.log('Cache hit:', event.request.url);
return cachedResponse;
}
// Otherwise, fetch the resource from the network
return fetch(event.request).then((networkResponse) => {
// Check if the response is valid
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
console.log('Fetch failed:', event.request.url);
return networkResponse;
}
// Clone the response to store in the cache and return the original response
const responseToCache = networkResponse.clone();
// Open a cache and store the fetched resource for future use
caches.open(cacheName).then((cache) => {
console.log('Cache miss - storing:', event.request.url);
cache.put(event.request, responseToCache);
});
return networkResponse;
});
})
);
});