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
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>
.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.