1
1
// sw.js
2
2
const CACHE_NAME = "ttc-cache-v1" ;
3
- const urlsToCache = [
4
- "/" ,
5
- "/index.html" ,
6
- "/css/*.css" ,
7
- "/js/editor.js" ,
8
- "/favicon-150.png" ,
9
- "/favicon-48.png" ,
10
- "/favicon-512.png" ,
11
- "/favicon-192.png" ,
12
- ] ;
13
3
14
- // Install the service worker
15
- self . addEventListener ( "install" , ( event ) => {
16
- event . waitUntil (
17
- caches . open ( CACHE_NAME ) . then ( ( cache ) => {
18
- return cache . addAll ( urlsToCache ) ;
4
+ // Fetch event: Cache responses immediately after fetching
5
+ self . addEventListener ( "fetch" , ( event ) => {
6
+ event . respondWith (
7
+ caches . match ( event . request ) . then ( ( cachedResponse ) => {
8
+ // If a match is found in the cache, return it; otherwise, fetch from network
9
+ return (
10
+ cachedResponse ||
11
+ fetch ( event . request ) . then ( ( networkResponse ) => {
12
+ // Check if we received a valid response
13
+ if (
14
+ ! networkResponse ||
15
+ networkResponse . status !== 200 ||
16
+ networkResponse . type !== "basic"
17
+ ) {
18
+ return networkResponse ; // Return the response if it's not valid for caching
19
+ }
20
+
21
+ // Clone the response because we can only use it once
22
+ const responseToCache = networkResponse . clone ( ) ;
23
+
24
+ // Open the cache and store the response
25
+ caches . open ( CACHE_NAME ) . then ( ( cache ) => {
26
+ cache . put ( event . request , responseToCache ) ;
27
+ } ) ;
28
+
29
+ return networkResponse ; // Return the original network response
30
+ } )
31
+ ) ;
19
32
} )
20
33
) ;
21
34
} ) ;
22
35
23
- // Fetch the cached assets
24
- self . addEventListener ( "fetch" , ( event ) => {
25
- event . respondWith (
26
- caches . match ( event . request ) . then ( ( response ) => {
27
- return response || fetch ( event . request ) ;
36
+ // Activate event: Clean up old caches if necessary
37
+ self . addEventListener ( "activate" , ( event ) => {
38
+ const cacheWhitelist = [ CACHE_NAME ] ;
39
+ event . waitUntil (
40
+ caches . keys ( ) . then ( ( cacheNames ) => {
41
+ return Promise . all (
42
+ cacheNames . map ( ( cacheName ) => {
43
+ if ( cacheWhitelist . indexOf ( cacheName ) === - 1 ) {
44
+ return caches . delete ( cacheName ) ;
45
+ }
46
+ } )
47
+ ) ;
28
48
} )
29
49
) ;
30
- } ) ;
50
+ } ) ;
0 commit comments