sanch1tx commited on
Commit
746acaf
·
verified ·
1 Parent(s): 2678cde

Create sw.js

Browse files
Files changed (1) hide show
  1. sw.js +79 -0
sw.js ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const CACHE_NAME = 'melofy-cache-v1';
2
+ const urlsToCache = [
3
+ '/',
4
+ '/index.html'
5
+ // Add other static assets here if they are not inlined, e.g., '/style.css'
6
+ ];
7
+
8
+ // Install event: caches the core application shell.
9
+ self.addEventListener('install', event => {
10
+ event.waitUntil(
11
+ caches.open(CACHE_NAME)
12
+ .then(cache => {
13
+ console.log('Opened cache');
14
+ return cache.addAll(urlsToCache);
15
+ })
16
+ );
17
+ self.skipWaiting();
18
+ });
19
+
20
+ // Fetch event: serves assets from cache first for offline capability.
21
+ self.addEventListener('fetch', event => {
22
+ // We only want to cache GET requests.
23
+ if (event.request.method !== 'GET') {
24
+ return;
25
+ }
26
+
27
+ event.respondWith(
28
+ caches.match(event.request)
29
+ .then(response => {
30
+ // Cache hit - return response
31
+ if (response) {
32
+ return response;
33
+ }
34
+
35
+ // Not in cache - fetch from network, then cache it.
36
+ return fetch(event.request).then(
37
+ response => {
38
+ // Check if we received a valid response
39
+ if(!response || response.status !== 200 || response.type !== 'basic') {
40
+ return response;
41
+ }
42
+
43
+ // IMPORTANT: Clone the response. A response is a stream
44
+ // and can only be consumed once. We need one for the browser
45
+ // and one for the cache.
46
+ const responseToCache = response.clone();
47
+
48
+ caches.open(CACHE_NAME)
49
+ .then(cache => {
50
+ // We don't cache API calls to avoid stale data.
51
+ // Adjust this condition if you have other API endpoints.
52
+ if (!event.request.url.includes('/search/') && !event.request.url.includes('/lyrics')) {
53
+ cache.put(event.request, responseToCache);
54
+ }
55
+ });
56
+
57
+ return response;
58
+ }
59
+ );
60
+ })
61
+ );
62
+ });
63
+
64
+ // Activate event: cleans up old caches.
65
+ self.addEventListener('activate', event => {
66
+ const cacheWhitelist = [CACHE_NAME];
67
+ event.waitUntil(
68
+ caches.keys().then(cacheNames => {
69
+ return Promise.all(
70
+ cacheNames.map(cacheName => {
71
+ if (cacheWhitelist.indexOf(cacheName) === -1) {
72
+ return caches.delete(cacheName);
73
+ }
74
+ })
75
+ );
76
+ })
77
+ );
78
+ return self.clients.claim();
79
+ });