1- const CACHE_NAME = "vault-cache-v14" ;
1+ const APP_VERSION = "1" ;
2+ const CACHE_NAME = `vault-cache-v${ APP_VERSION } ` ;
23const FILES_TO_CACHE = [
3- "/" ,
44 "/index.html" ,
55 "/styles.css" ,
66 "/js/app.js" ,
@@ -13,13 +13,10 @@ const FILES_TO_CACHE = [
1313 "/icons/favicon.ico"
1414] ;
1515
16-
1716// Install: cache everything
1817self . addEventListener ( "install" , ( event ) => {
1918 event . waitUntil (
20- caches . open ( CACHE_NAME ) . then ( ( cache ) => {
21- return cache . addAll ( FILES_TO_CACHE ) ;
22- } )
19+ caches . open ( CACHE_NAME ) . then ( ( cache ) => cache . addAll ( FILES_TO_CACHE ) )
2320 ) ;
2421 self . skipWaiting ( ) ;
2522} ) ;
@@ -30,21 +27,40 @@ self.addEventListener("activate", (event) => {
3027 caches . keys ( ) . then ( ( keyList ) =>
3128 Promise . all (
3229 keyList . map ( ( key ) => {
33- if ( key !== CACHE_NAME ) {
34- return caches . delete ( key ) ;
35- }
30+ if ( key !== CACHE_NAME ) return caches . delete ( key ) ;
3631 } )
3732 )
3833 )
3934 ) ;
4035 self . clients . claim ( ) ;
4136} ) ;
4237
43- // Fetch: serve from cache when offline
38+ // Fetch: cache-first for offline
4439self . addEventListener ( "fetch" , ( event ) => {
40+ if ( event . request . method !== "GET" ) return ;
41+
4542 event . respondWith (
46- caches . match ( event . request ) . then ( ( response ) => {
47- return response || fetch ( event . request ) ;
43+ caches . match ( event . request , { ignoreSearch : true } ) . then ( ( cached ) => {
44+ if ( cached ) return cached ;
45+
46+ return fetch ( event . request )
47+ . then ( ( response ) => {
48+ const clone = response . clone ( ) ;
49+ caches . open ( CACHE_NAME ) . then ( ( cache ) => {
50+ cache . put ( event . request , clone ) ;
51+ } ) ;
52+ return response ;
53+ } )
54+ . catch ( ( ) => {
55+ if ( event . request . mode === "navigate" ) {
56+ return caches . match ( "/index.html" ) ;
57+ }
58+ } ) ;
4859 } )
4960 ) ;
5061} ) ;
62+
63+ // Force update activation from app.js
64+ self . addEventListener ( "message" , ( event ) => {
65+ if ( event . data === "SKIP_WAITING" ) self . skipWaiting ( ) ;
66+ } ) ;
0 commit comments