soiz1 commited on
Commit
6c4a603
·
1 Parent(s): 0e2cd10

Create service-worker.js

Browse files
Files changed (1) hide show
  1. service-worker.js +51 -0
service-worker.js ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const CACHE_NAME = 'my-cache-v1';
2
+ const OFFLINE_URLS = [
3
+ '/',
4
+ '/index.html',
5
+ // 必要に応じてCSSやJSも追加
6
+ ];
7
+
8
+ // インストール:キャッシュを保存
9
+ self.addEventListener('install', event => {
10
+ event.waitUntil(
11
+ caches.open(CACHE_NAME).then(cache => {
12
+ return cache.addAll(OFFLINE_URLS);
13
+ })
14
+ );
15
+ self.skipWaiting(); // すぐに有効化
16
+ });
17
+
18
+ // アクティベート:古いキャッシュ削除
19
+ self.addEventListener('activate', event => {
20
+ event.waitUntil(
21
+ caches.keys().then(keys =>
22
+ Promise.all(
23
+ keys.map(key => {
24
+ if (key !== CACHE_NAME) {
25
+ return caches.delete(key);
26
+ }
27
+ })
28
+ )
29
+ )
30
+ );
31
+ self.clients.claim(); // 即時制御
32
+ });
33
+
34
+ // フェッチ:ネット優先、失敗時にキャッシュ
35
+ self.addEventListener('fetch', event => {
36
+ event.respondWith(
37
+ fetch(event.request)
38
+ .then(response => {
39
+ // ネットから取得できたのでキャッシュ更新
40
+ const responseClone = response.clone();
41
+ caches.open(CACHE_NAME).then(cache => {
42
+ cache.put(event.request, responseClone);
43
+ });
44
+ return response;
45
+ })
46
+ .catch(() => {
47
+ // ネットがだめならキャッシュから
48
+ return caches.match(event.request);
49
+ })
50
+ );
51
+ });