skip to Main Content

I’m rather new to service workers. So excuse me in advance if my question is simple.
I’m trying to implement an offline page for my React application. Every one is suggesting the following code:

sw.addEventListener("fetch", (event) => {
  
    event.respondWith(
      caches.match(event.request).then((cachedResponse) => {
        return (
          cachedResponse ||
          fetch(event.request)
            .then((networkResponse) => {
              return caches.open('dynamic').then((cache) => {
                cache
                  .put(event.request, networkResponse.clone())
                  .catch(() => {});
                return networkResponse;
              });
            })
            .catch(() => {
              return caches.open(STATIC_ASSETS_NAME).then((cache) => {
                return cache.match("/offline.html").then(() => {
                  return new Response("/offline.html", {
                    headers: { "Content-Type": "text/html" },
                  });
                });
              });
            })
        );
      })
    );
  
});

The problem is that in React, responses basically need js file which represents a component, not an html file. So this doesn’t work for React and throws error.
Can anyone please help me out? thanks

2

Answers


  1. It sounds like you need react-detect-offline (it has also downloadable type support). You can place your top level component in <Online> and fallback component in <Offline>.

    Login or Signup to reply.
  2. In above code, you need to ensure that the offline page includes the necessary JavaScript to bootstrap the React application. I adjusted your service worker.

    const STATIC_ASSETS_NAME = 'static-assets';
    const DYNAMIC_CACHE_NAME = 'dynamic';
    const OFFLINE_URL = '/offline.html';
    
    // Precache the offline page during the service worker installation
    self.addEventListener('install', (event) => {
      event.waitUntil(
        caches.open(STATIC_ASSETS_NAME)
          .then((cache) => cache.add(OFFLINE_URL))
      );
    });
    
    // Handle fetch events
    self.addEventListener('fetch', (event) => {
      event.respondWith(
        caches.match(event.request).then((cachedResponse) => {
          if (cachedResponse) {
            // Return the cached response if found
            return cachedResponse;
          }
          // Fallback to network
          return fetch(event.request).then((networkResponse) => {
            return caches.open(DYNAMIC_CACHE_NAME).then((cache) => {
              // Cache the dynamic content
              cache.put(event.request, networkResponse.clone()).catch(() => {});
              return networkResponse;
            });
          }).catch(() => {
            // Return the offline page if both cache and network fail
            return caches.match(OFFLINE_URL).then((offlineResponse) => {
              return offlineResponse || new Response('Offline page missing', {
                status: 404,
                headers: { 'Content-Type': 'text/plain' }
              });
            });
          });
        })
      );
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search