-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsServiceWorker.js
106 lines (96 loc) · 2.39 KB
/
jsServiceWorker.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Виноградов С.В. https://github.com/fdsc/timer
// chrome://inspect/#service-workers
// about:debugging
// https://developer.mozilla.org/ru/docs/Web/API/Service_Worker_API/Using_Service_Workers
// https://developer.mozilla.org/en-US/docs/Web/API/Cache
const version = 'Fgvh2yOexbi8';
self.addEventListener
(
'install',
function(event)
{
// Событие будет считаться незавершённым, пока воркер успешно не проинициализируется
event.waitUntil
(
caches.open(version)
.then
(/*
function(cache)
{
return cache.addAll
([
'index.html',
'jsTimer.js',
'B4v45ZrQwRVM.css'
]);
}*/
)
);
}
);
self.addEventListener
(
'fetch',
function(event)
{
// Загружаем из сети
var request = fetch(event.request)
.then
(
function (response)
{
let responseClone = response.clone();
// Кешируем заново
caches.open(version)
.then
(
function (cache)
{
console.info("TimerJS: cache.put " + event.request.url);
cache.put(event.request, responseClone);
}
);
console.info("TimerJS: service worker load from internet for url " + event.request.url);
return response;
}
)
.catch
(
function(error)
{
console.info("TimerJS: service worker load from the cache for url " + event.request.url);
console.info(error);
// Возвращаем запрошенный ресурс из кеша
return caches.match(event.request)
.then
(
function(response)
{
if (response !== undefined)
{
return response.clone();
}
else
{
// return caches.match('error.png');
// https://developer.mozilla.org/en-US/docs/Web/API/Response
var r = new Response
(
'Network is unreilable or error occured (TimerJS)',
{
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
// Request Timeout
"status" : 408,
"statusText": "Network is unreilable or error occured (TimerJS)"
}
);
console.error("TimerJS: service worker: network is unreilable or error occured");
return r;
}
}
);
}
);
event.respondWith(request);
}
);