File size: 2,460 Bytes
7ab4189
cc712f9
7ab4189
510eafa
 
 
 
 
 
 
 
 
 
 
084200d
 
 
 
 
 
 
c7a1426
 
7ab4189
cc712f9
 
510eafa
cc712f9
 
 
 
 
 
510eafa
c7a1426
 
7ab4189
 
 
 
 
cc712f9
 
7ab4189
 
 
 
cc712f9
7ab4189
 
cc712f9
7ab4189
cc712f9
 
 
757946c
 
 
cc712f9
510eafa
 
cc712f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510eafa
c7a1426
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const CACHE_NAME = 'dance-video-cache-v' + new Date().getTime(); // 毎回異なるキャッシュ名

const ASSETS_TO_CACHE = [
  '/',
  '/index.html',
  '/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(); // 新しいSWを即時アクティベート
  
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('Opened cache');
        return cache.addAll(ASSETS_TO_CACHE.map(url => new Request(url, {cache: 'reload'})));
      })
      .catch(error => console.log('Cache addAll error:', error))
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => self.clients.claim()) // すべてのクライアントを制御
  );
});

self.addEventListener('fetch', event => {
  // 外部リソースはキャッシュしない
  if (event.request.url.startsWith('http') && 
      !event.request.url.startsWith(self.location.origin)) {
    event.respondWith(fetch(event.request));
    return;
  }
  
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // キャッシュがあれば返す、なければフェッチしてキャッシュ
        return response || fetch(event.request).then(response => {
          // クローンを作成(ストリームは一度しか読めないため)
          const responseToCache = response.clone();
          
          caches.open(CACHE_NAME)
            .then(cache => cache.put(event.request, responseToCache));
            
          return response;
        });
      })
      .catch(error => {
        console.log('Fetch failed; returning offline page:', error);
        return caches.match('/offline.html'); // オフラインページがあれば
      })
  );
});