Skip to content

Commit

Permalink
only cache all assets if pwa installed
Browse files Browse the repository at this point in the history
  • Loading branch information
secondl1ght committed Jun 1, 2023
1 parent 6aace94 commit 8faa162
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
10 changes: 10 additions & 0 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<html lang="en">
<head>
<script>
// theme
if (
localStorage.theme === 'dark' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
Expand All @@ -10,6 +11,15 @@
} else {
document.documentElement.classList.remove('dark');
}

// service worker
navigator.serviceWorker?.ready.then((registration) => {
const appInstalled = window.matchMedia('(display-mode: standalone)').matches;

if (appInstalled) {
registration.active.postMessage('CACHE_ASSETS');
}
});
</script>
<meta name="theme-color" content="#0B9072" />
<meta name="keywords" content="bitcoin, open source, map" />
Expand Down
20 changes: 16 additions & 4 deletions src/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ const ASSETS = [
];

self.addEventListener('install', (event) => {
// Create a new cache and add all files to it
async function addFilesToCache() {
// Create a new cache and add offline file to it
async function addFileToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
await cache.add('/offline.html');
}

event.waitUntil(addFilesToCache());
event.waitUntil(addFileToCache());
});

self.addEventListener('activate', (event) => {
Expand All @@ -30,6 +30,18 @@ self.addEventListener('activate', (event) => {
event.waitUntil(deleteOldCaches());
});

self.addEventListener('message', async (event) => {
if (event.data === 'CACHE_ASSETS') {
// Create a new cache and add all files to it
const cache = await caches.open(CACHE);
const cached = await cache.match('/cached.txt');

if (cached) return;

event.waitUntil(await cache.addAll(ASSETS));
}
});

self.addEventListener('fetch', (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET') return;
Expand Down
Empty file added static/cached.txt
Empty file.

0 comments on commit 8faa162

Please sign in to comment.