Service Workers缓存

之前一篇文章介绍了Service Workers的基本使用。那么现在这篇文章介绍一下Service Workers拦截请求并缓存。

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
var CACHE_VERSION = 1;

// Shorthand identifier mapped to specific versioned cache.
var CURRENT_CACHES = {
font: 'font-cache-v' + CACHE_VERSION
};

var urlsToCache = [
'/',
'./main.css',
'http://localhost:11080/gt/register2'
];

//service worker安装成功后开始缓存所需的资源
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CURRENT_CACHES['font'])
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});

//监听浏览器的所有fetch请求,对已经缓存的资源使用本地缓存回复
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
//该fetch请求已经缓存
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
hi you can see me