-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
69 lines (64 loc) · 2.49 KB
/
Copy pathservice-worker.js
File metadata and controls
69 lines (64 loc) · 2.49 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
var CACHE_NAME = 'mycache-3'
self.addEventListener('install', function(event) {
console.log('Installing Service Worker')
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
cache.addAll([
'/',
'offline.html',
'index.html',
'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css',
'assets/css/common.css',
'assets/css/index.css',
'https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/relativeTime.min.js',
'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js',
'assets/js/common.js',
'assets/js/index.js',
'assets/images/logo.svg',
])
})
)
})
self.addEventListener('activate', function(event) {
console.log('Activating Service Worker')
event.waitUntil(
caches.keys()
.then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CACHE_NAME) {
console.log('[Service Worker] Removing old cache.', key);
return caches.delete(key);
}
}));
})
);
self.clients.claim()
})
self.addEventListener('fetch', function(event) {
console.log('Detected a request', event.request)
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
// cache first strategy
console.log('Found in cache: ', event.request.url)
return response
} else {
return fetch(event.request).then((response) => {
// fron network (we have internet)
//'https://www.ferasjobeir.com/api/posts?page=1'
return caches.open(CACHE_NAME).then(function(cache) {
// adding dynamic cache
cache.put(event.request, response.clone())
return response
})
}).catch((error) => {
// failed to load from cache and failed to access the network
return caches.open(CACHE_NAME).then(cache => {
return cache.match('offline.html')
})
})
}
})
)
})