izuemon commited on
Commit
dc050ef
·
verified ·
1 Parent(s): 650466e

Update p1/sw.js

Browse files
Files changed (1) hide show
  1. p1/sw.js +56 -12
p1/sw.js CHANGED
@@ -1,6 +1,6 @@
1
  const CACHE_NAME = 'p-cache-v1';
2
 
3
- self.addEventListener('install', (event) => {
4
  self.skipWaiting();
5
  });
6
 
@@ -10,37 +10,81 @@ self.addEventListener('activate', (event) => {
10
 
11
  self.addEventListener('fetch', (event) => {
12
 
13
- const url = new URL(event.request.url);
 
14
 
15
- // URLパラメータを無視
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  const cacheUrl = url.origin + url.pathname;
17
 
18
  event.respondWith(
 
19
  caches.match(cacheUrl).then((cached) => {
20
 
 
21
  if (cached) {
22
  return cached;
23
  }
24
 
25
- return fetch(event.request).then((response) => {
 
 
 
 
 
 
26
 
27
- // GETだけキャッシュ
28
- if (event.request.method === 'GET') {
29
 
30
- const responseClone = response.clone();
31
 
32
  caches.open(CACHE_NAME).then((cache) => {
33
- cache.put(cacheUrl, responseClone);
34
  });
35
  }
36
 
37
  return response;
 
38
  }).catch(() => {
39
 
40
- // index fallback
41
- if (url.pathname.startsWith('/p1/')) {
42
- return caches.match('/p1/index.html');
43
- }
44
  });
45
  })
46
  );
 
1
  const CACHE_NAME = 'p-cache-v1';
2
 
3
+ self.addEventListener('install', () => {
4
  self.skipWaiting();
5
  });
6
 
 
10
 
11
  self.addEventListener('fetch', (event) => {
12
 
13
+ const req = event.request;
14
+ const url = new URL(req.url);
15
 
16
+ // =========================
17
+ // chrome-extension除外
18
+ // =========================
19
+
20
+ if (
21
+ url.protocol !== 'http:' &&
22
+ url.protocol !== 'https:'
23
+ ) {
24
+ return;
25
+ }
26
+
27
+ // =========================
28
+ // 自サイト以外除外
29
+ // =========================
30
+
31
+ if (url.origin !== location.origin) {
32
+ return;
33
+ }
34
+
35
+ // =========================
36
+ // /p1/ 以外除外
37
+ // =========================
38
+
39
+ if (!url.pathname.startsWith('/p1/')) {
40
+ return;
41
+ }
42
+
43
+ // =========================
44
+ // Range Request除外
45
+ // 動画/音声再生を壊さない
46
+ // =========================
47
+
48
+ if (req.headers.has('range')) {
49
+ return;
50
+ }
51
+
52
+ // URLパラメータ無視
53
  const cacheUrl = url.origin + url.pathname;
54
 
55
  event.respondWith(
56
+
57
  caches.match(cacheUrl).then((cached) => {
58
 
59
+ // キャッシュ優先
60
  if (cached) {
61
  return cached;
62
  }
63
 
64
+ // 通常fetch
65
+ return fetch(req).then((response) => {
66
+
67
+ // fetch失敗時対策
68
+ if (!response || response.status !== 200) {
69
+ return response;
70
+ }
71
 
72
+ // GETのみ
73
+ if (req.method === 'GET') {
74
 
75
+ const cloned = response.clone();
76
 
77
  caches.open(CACHE_NAME).then((cache) => {
78
+ cache.put(cacheUrl, cloned);
79
  });
80
  }
81
 
82
  return response;
83
+
84
  }).catch(() => {
85
 
86
+ // offline fallback
87
+ return caches.match('/p1/index.html');
 
 
88
  });
89
  })
90
  );