PWA-缓存
基础
PWA强大的离线能力就在于Service Worker拦截请求及提供缓存的能力,Service Worker的缓存能力比较强大,它能够赋予你更加精确控制缓存的能力。示例页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>缓存</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<h1></h1>
<img src="1.jpg" alt="1" />
<script>
navigator
.serviceWorker
.register('sw.js')
.then(function (reg) {
console.log(reg.scope)
})
.catch(function (err) {
console.log(err)
})
</script>
</body>
</html>
安装预缓存
在SW安装阶段,可以获取资源并为下次访问准备好缓存,示例
var cacheName = 'test'
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll(['1.jpg']))
)
})
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(resp => {
if (resp) {
return resp;
}
return fetch(event.request)
})
)
})
拦截并缓存
安装预缓存适用于知道缓存的内容的情况,当预先不知道到缓存的内容的情况下可以拦截请求并进行缓存,方便下次使用
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(resp => {
if (resp) {
return resp;
}
var requestToCache = event.request.clone();
return fetch(requestToCache).then(
(response) => {
if (!response || response.status != 200) {
return response;
}
var responseToCache = response.clone();
caches.open(cacheName).then(cache => {
cache.put(requestToCache, requestToCache)
})
return response;
}
)
})
)
})
其他
- 缓存版本控制(hash)
- workbox