Skip to content

Commit

Permalink
don't cache requests, show offline page instead when not online
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmaSd committed Apr 24, 2024
1 parent 68d1aea commit bdf6868
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 15 deletions.
31 changes: 31 additions & 0 deletions static/offline.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offline</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f2f2f2;
}
.container {
margin-top: 100px;
}
h1 {
color: #333;
}
p {
color: #666;
}
</style>
</head>
<body>
<div class="container">
<h1>Offline Page</h1>
<p>Sorry, it seems like you're offline. This app requires an internet connection to function.</p>
</div>
</body>
</html>

29 changes: 14 additions & 15 deletions static/sw.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
// Cache requests so the app can work offline
// https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers
const cacheName = "myapp";
const offlinePage = "/offline.html";

self.addEventListener("fetch", (e) => {
e.respondWith(
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.add(offlinePage);
}),
);
});

self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
try {
const response = await fetch(e.request);
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching resource: ${e.request.url}`);
cache.put(e.request, response.clone());
return response;
return await fetch(event.request);
} catch {
// if we have no network access, try to use the cache
const response = await caches.match(e.request);
console.log(`[Service Worker] Using cached resource: ${e.request.url}`);
if (response) {
return response;
}
// If no cache is available, respond with the offline page
return caches.match(offlinePage);
}
})(),
);
Expand Down

0 comments on commit bdf6868

Please sign in to comment.