1- const CACHE_VERSION = 'SW_VERSION_PLACEHOLDER' ;
1+ const CACHE_VERSION = 'SW_VERSION_PLACEHOLDER' === 'SW_VERSION_PLACEHOLDER' ? 'dev-' + Date . now ( ) : 'SW_VERSION_PLACEHOLDER' ;
22const CACHE_NAME = `document-editor-${ CACHE_VERSION } ` ;
33const ASSETS_TO_CACHE = [ './' , './index.html' , './img/64.png' ] ;
44
@@ -30,15 +30,25 @@ self.addEventListener('activate', (event) => {
3030
3131// Fetch event: Stale-While-Revalidate strategy
3232self . addEventListener ( 'fetch' , ( event ) => {
33- // Only handle GET requests
33+ const url = new URL ( event . request . url ) ;
34+
35+ // 1. Only handle GET requests
3436 if ( event . request . method !== 'GET' ) return ;
3537
38+ // 2. Only handle same-origin requests to avoid caching external APIs/documents
39+ if ( url . origin !== self . location . origin ) return ;
40+
41+ // 3. Skip caching for requests with dynamic parameters (like ?file= or ?src=)
42+ // These are typically documents being edited, which should always be fresh.
43+ if ( url . searchParams . has ( 'file' ) || url . searchParams . has ( 'src' ) ) return ;
44+
45+ // 4. Stale-While-Revalidate Strategy
3646 event . respondWith (
3747 caches . match ( event . request ) . then ( ( cachedResponse ) => {
3848 const fetchPromise = fetch ( event . request )
3949 . then ( ( networkResponse ) => {
40- // Cache the new response
41- if ( networkResponse && networkResponse . status === 200 ) {
50+ // Only cache valid 200 responses
51+ if ( networkResponse && networkResponse . status === 200 && networkResponse . type === 'basic' ) {
4252 const responseToCache = networkResponse . clone ( ) ;
4353 caches . open ( CACHE_NAME ) . then ( ( cache ) => {
4454 cache . put ( event . request , responseToCache ) ;
@@ -47,12 +57,15 @@ self.addEventListener('fetch', (event) => {
4757 return networkResponse ;
4858 } )
4959 . catch ( ( ) => {
50- // If network fails and no cache, just let it fail
60+ // If network fails, return the cached version if we have it
5161 return cachedResponse ;
5262 } ) ;
5363
54- // Return cached response immediately if available, otherwise wait for network
55- return cachedResponse || fetchPromise ;
64+ // Use event.waitUntil to ensure the fetch/cache update continues in background
65+ if ( ! cachedResponse ) {
66+ return fetchPromise ;
67+ }
68+ return cachedResponse ;
5669 } ) ,
5770 ) ;
5871} ) ;
0 commit comments