Spaces:
Running
Running
const INDEX_CACHE = 'index-cache-v-' + new Date().getTime(); // index.htmlは毎回更新 | |
const VIDEO_CACHE = 'static-video-cache'; // 動画は一度キャッシュして再利用 | |
const INDEX_ASSETS = [ | |
'/', | |
'/index.html' | |
]; | |
const VIDEO_ASSETS = [ | |
'/videos/k-back-human.mp4', | |
'/videos/k-back-stick-human.mp4', | |
'/videos/k-back-stick.mp4', | |
'/videos/k-human.mp4', | |
'/videos/k-stick-human.mp4', | |
'/videos/m-back-human.mp4', | |
'/videos/m-back-stick-human.mp4', | |
'/videos/m-back-stick.mp4', | |
'/videos/m-human.mp4', | |
'/videos/m-stick-human.mp4', | |
'/videos/e-back-human.mp4', | |
'/videos/e-back-stick-human.mp4', | |
'/videos/e-back-stick.mp4', | |
'/videos/e-human.mp4', | |
'/videos/e-stick-human.mp4' | |
]; | |
self.addEventListener('install', event => { | |
self.skipWaiting(); | |
event.waitUntil( | |
Promise.all([ | |
caches.open(INDEX_CACHE) | |
.then(cache => cache.addAll(INDEX_ASSETS.map(url => new Request(url, { cache: 'reload' })))), | |
caches.open(VIDEO_CACHE) | |
.then(cache => cache.addAll(VIDEO_ASSETS)) | |
]) | |
); | |
}); | |
self.addEventListener('activate', event => { | |
event.waitUntil( | |
caches.keys().then(cacheNames => { | |
return Promise.all( | |
cacheNames.map(name => { | |
if (name !== INDEX_CACHE && name !== VIDEO_CACHE) { | |
return caches.delete(name); | |
} | |
}) | |
); | |
}).then(() => self.clients.claim()) | |
); | |
}); | |
self.addEventListener('fetch', event => { | |
const url = new URL(event.request.url); | |
// 外部リソースはキャッシュ対象外 | |
if (url.origin !== self.location.origin) { | |
return; | |
} | |
if (url.pathname === '/' || url.pathname.endsWith('index.html')) { | |
// 毎回新しい index.html をキャッシュから取得 | |
event.respondWith( | |
caches.open(INDEX_CACHE) | |
.then(cache => cache.match(event.request) | |
.then(response => response || fetch(event.request))) | |
); | |
return; | |
} | |
if (url.pathname.startsWith('/videos/')) { | |
// 動画は static-video-cache から | |
event.respondWith( | |
caches.match(event.request) | |
.then(response => response || fetch(event.request) | |
.then(networkResponse => { | |
return caches.open(VIDEO_CACHE).then(cache => { | |
cache.put(event.request, networkResponse.clone()); | |
return networkResponse; | |
}); | |
})) | |
); | |
return; | |
} | |
// その他リクエスト | |
event.respondWith( | |
caches.match(event.request) | |
.then(response => response || fetch(event.request)) | |
.catch(() => caches.match('/offline.html')) | |
); | |
}); | |