49 lines
1.1 KiB
JavaScript
49 lines
1.1 KiB
JavaScript
const CACHE = 'music-box-v3';
|
|
|
|
self.addEventListener('install', e => {
|
|
self.skipWaiting();
|
|
e.waitUntil(
|
|
caches.open(CACHE).then(c => c.addAll([
|
|
'./',
|
|
'./index.html',
|
|
'./zen_box.js',
|
|
'./zen_box.css',
|
|
'./playlist.json'
|
|
]))
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', e => {
|
|
e.waitUntil(clients.claim());
|
|
});
|
|
|
|
self.addEventListener('fetch', e => {
|
|
// 音频文件直接使用 Network Only
|
|
if (e.request.url.includes('.mp3') || e.request.url.includes('oss')) {
|
|
e.respondWith(fetch(e.request));
|
|
return;
|
|
}
|
|
|
|
// playlist.json 使用 Network First
|
|
if (e.request.url.includes('playlist.json')) {
|
|
e.respondWith(
|
|
fetch(e.request)
|
|
.then(networkResponse => {
|
|
return caches.open(CACHE).then(cache => {
|
|
cache.put(e.request, networkResponse.clone());
|
|
return networkResponse;
|
|
});
|
|
})
|
|
.catch(() => {
|
|
return caches.match(e.request);
|
|
})
|
|
);
|
|
return;
|
|
}
|
|
|
|
// 其他文件(App Shell)使用 Cache First
|
|
e.respondWith(
|
|
caches.match(e.request).then(r => r || fetch(e.request))
|
|
);
|
|
});
|