- server-worker想要本地测试的话,需要的ip必须是localhost或者127.0.0.1
- server-worker的使用必须是在https协议下
- test.js
<!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>server worker</title>
</head>
<body>
</body>
<script>
if ('serviceWorker' in navigator) {
var version = '1.0.1'
window.addEventListener('load', function () {
navigator.serviceWorker.ready.then(registration => {
console.log(registration)
}).catch(err => {
console.log(err)
})
navigator.serviceWorker.register('/test/test1-css/test.js', {
scope: '/test/test1-css/'
}).then(function (registration) {
// worker文件(test.js)可能会因为浏览器缓存问题,当文件有了变化时,浏览器里还是旧的文件。这会导致更新得不到响应。
if (localStorage.getItem('sw_version') !== version) {
registration.update().then(function () {
localStorage.setItem('sw_version', version)
})
}
// 注册成功
console.log('ServiceWorker registration successful with scope: ', registration.scope)
}).catch(function (err) {
// 注册失败:
console.log('ServiceWorker registration failed: ', err)
})
})
}
</script>
</html>
-
监听 service worker 的 install 事件
// on install 的优点是第二次访问即可离线,缺点是需要将需要缓存的 URL 在编译时插入到脚本中,增加代码量和降低可维护性
// 监听 service worker 的 install 事件 // on install 的优点是第二次访问即可离线,缺点是需要将需要缓存的 URL 在编译时插入到脚本中,增加代码量和降低可维护性; const ENV = 'development' this.addEventListener('install', function (event) { console.log('test') // 本地开发时希望重新加载后立即激活 if (ENV === 'development') { self.skipWaiting() return true } // 如果监听到了 service worker 已经安装成功的话,就会调用 event.waitUntil 回调函数 event.waitUntil( // 安装成功后操作 CacheStorage 缓存,使用之前需要先通过 caches.open() 打开对应缓存空间。 caches.open('my-test-cache-v1').then(function (cache) { console.log('cache:', cache) // 通过 cache 缓存对象的 addAll 方法添加 precache 缓存 // 以下资源被加载过一次之后将开始被缓存 return cache.addAll(['/test/test1-css/index.html', '/test/test1-css/index2.html']) }).catch(function (err) { console.log(err) }) ) })
2.on fetch 的优点是无需更改编译过程,也不会产生额外的流量,缺点是需要多一次访问才能离线可用。
this.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
// 来来来,代理可以搞一些代理的事情
console.log(response)
// 如果 Service Worker 有自己的返回,就直接返回,减少一次 http 请求
if (response) {
return response
}
// 如果 service worker 没有返回,那就得直接请求真实远程服务
var request = event.request.clone()
// 把原始请求拷过来
return fetch(request).then(function (httpRes) {
// http请求的返回已被抓到,可以处置了。
console.log(httpRes)
// 请求失败了,直接返回失败的结果就好了。
if (!httpRes || httpRes.status !== 200) {
return httpRes
}
// 请求成功的话,将请求缓存起来。
var responseClone = httpRes.clone()
caches.open('my-test-cache-v1').then(function (cache) {
cache.put(event.request, responseClone)
})
return httpRes
})
})
)
})
3. 安装阶段跳过等待,直接进入 active,如果希望在有了新版本时,所有的页面都得到及时自动更新
self.addEventListener('install', function (event) {
event.waitUntil(self.skipWaiting())
})
self.addEventListener('activate', function (event) {
event.waitUntil(
Promise.all([
// 更新客户端
self.clients.claim(),
// 清理旧版本
caches.keys().then(function (cacheList) {
return Promise.all(
cacheList.map(function (cacheName) {
if (cacheName !== 'my-test-cache-v1') {
return caches.delete(cacheName)
}
}))
})]))
})