47 lines
1.3 KiB
JavaScript
47 lines
1.3 KiB
JavaScript
const CACHE = 'intern-log-v1'
|
|
const CORE = ['./', './index.html']
|
|
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(caches.open(CACHE).then(c => c.addAll(CORE)).then(() => self.skipWaiting()))
|
|
})
|
|
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(
|
|
caches.keys()
|
|
.then(keys => Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k))))
|
|
.then(() => self.clients.claim())
|
|
)
|
|
})
|
|
|
|
self.addEventListener('fetch', event => {
|
|
const req = event.request
|
|
if (req.method !== 'GET') return
|
|
const url = new URL(req.url)
|
|
if (url.origin !== location.origin) return
|
|
|
|
// 页面导航:网络优先,离线回退缓存的应用壳
|
|
if (req.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(req)
|
|
.then(resp => {
|
|
const clone = resp.clone()
|
|
caches.open(CACHE).then(c => c.put('./index.html', clone))
|
|
return resp
|
|
})
|
|
.catch(() => caches.match('./index.html'))
|
|
)
|
|
return
|
|
}
|
|
|
|
// 静态资源:缓存优先,未命中时拉取并写入缓存
|
|
event.respondWith(
|
|
caches.match(req).then(hit => hit || fetch(req).then(resp => {
|
|
if (resp.ok) {
|
|
const clone = resp.clone()
|
|
caches.open(CACHE).then(c => c.put(req, clone))
|
|
}
|
|
return resp
|
|
}))
|
|
)
|
|
})
|