index.js
if ( navigator.serviceWorker ) {
console.log("cache index")
window.addEventListener("load", function(){
navigator.serviceWorker
.register('/serversWork.js')
.then(function(registration) {
console.log('service worker 注册成功')
})
.catch(function(err) {
console.log('servcie worker 注册失败')
})
})
}else{
console.log("chche error")
}
serversWork.js
let cachelist = [
"/index.js",
// "/favicon.ico",
"/_nuxt/app.js",
"/_nuxt/runtime.js",
"/_nuxt/commons.app.js",
"/_nuxt/pages/index.js",
// "/_nuxt/930f2fe73ad8f77ebbc1.js",
]
self.addEventListener('install', e => {
e.waitUntil(
caches.open('my-cache').then(function (cache) {
// console.log("cache success")
return cache.addAll(cachelist)
})
)
})
// 拦截所有请求事件
// 如果缓存中已经有请求的数据就直接用缓存,否则去请求数据
self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request).then(function (response) {
if ( response ) {
return response
}
return fetch( e.request );
})
)
})