-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathsw.js
More file actions
95 lines (87 loc) · 2.65 KB
/
sw.js
File metadata and controls
95 lines (87 loc) · 2.65 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const CACHE_NAME = 'freemovie-pwa-v3'; // Bump version
const STATIC_ASSETS = [
'/',
'/index.html',
'/assets/css/style.css',
'/assets/js/main.js',
'/assets/js/config.js',
'/assets/js/apiKeySwitcher.js',
'/assets/js/components/layout-shared.js',
'/assets/icons/favicon.ico',
'/images/default-freemovie-300.png'
];
const API_CACHE_NAME = 'freemovie-api-cache';
const IMAGE_CACHE_NAME = 'freemovie-image-cache';
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(STATIC_ASSETS);
})
);
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(
Promise.all([
caches.keys().then(keys => {
return Promise.all(keys.map(key => {
if (key !== CACHE_NAME && key !== API_CACHE_NAME && key !== IMAGE_CACHE_NAME) {
return caches.delete(key);
}
}));
}),
self.clients.claim()
])
);
});
self.addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
// 1. Static Assets: Cache-First
if (STATIC_ASSETS.includes(url.pathname) || url.origin === location.origin) {
event.respondWith(
caches.match(request).then(response => {
return response || fetch(request).then(fetchRes => {
return caches.open(CACHE_NAME).then(cache => {
cache.put(request, fetchRes.clone());
return fetchRes;
});
});
})
);
return;
}
// 2. Images (TMDB, OMDB, TVMaze): Cache-First, then Network
if (request.destination === 'image' || url.hostname.includes('tmdb.org') || url.hostname.includes('omdbapi.com')) {
event.respondWith(
caches.open(IMAGE_CACHE_NAME).then(cache => {
return cache.match(request).then(response => {
return response || fetch(request).then(fetchRes => {
cache.put(request, fetchRes.clone());
return fetchRes;
});
});
})
);
return;
}
// 3. API Requests: Stale-While-Revalidate
if (url.hostname.includes('api.themoviedb.org') || url.pathname.includes('omdb')) {
event.respondWith(
caches.open(API_CACHE_NAME).then(cache => {
return cache.match(request).then(cachedResponse => {
const fetchPromise = fetch(request).then(networkResponse => {
cache.put(request, networkResponse.clone());
return networkResponse;
});
return cachedResponse || fetchPromise;
});
})
);
return;
}
// 4. Default: Network with Cache Fallback
event.respondWith(
fetch(request).catch(() => caches.match(request))
);
});