The user is asking for guidance on building a progressive web app that includes offline caching and background sync using Service Workers. I’ll need to explain service worker registration, caching strategies, and the HTML for offline fallback. They didn’t mention a framework, so I’ll stick with vanilla JS/HTML/CSS but consider mentioning frameworks. I plan to produce an app shell, manifest.json, and a service worker that handles installation, activation, and fetch events while incorporating IndexedDB for offline data storage.Designing a PWA with Background Sync
I might consider using the IndexedDB library, but I want to keep things simple. Background Sync requires a queue, which I'll illustrate using IndexedDB with minimal code. However, there’s a chance that too much code can be overwhelming, especially for verbosity level 2. I’ll provide a minimal but functional example, including file structure, HTML, manifest, sw.js, and main.js, along with instructions for running it on HTTPS or localhost and managing offline caching with the Cache API. I'll also mention that Safari doesn't support Background Sync.Outlining PWA Features
I plan to outline the key features for a progressive web app (PWA). This includes the manifest.json file, implementing HTTPS, and setting up a service worker. For offline caching, I’ll ensure that static assets are cached on installation and provide navigation fallback to an offline.html page. Background sync will handle form posts stored offline to send once connectivity is restored.
I’ll include a folder structure and provide code in several parts, such as prerequisites, index.html with a simple form, main.js for registering the service worker, and sw.js for caching strategies and fetch event handling. Additionally, I'll consider intercepting fetch requests for background sync.Implementing IndexedDB for Sync
I’m outlining the typical pattern for handling form submissions. In main.js, when a form submits, I’ll store the message in IndexedDB and register a sync event using navigator.serviceWorker.ready.then(reg => reg.sync.register('sync-messages')). The service worker will then handle the 'sync' event tagged with 'sync-messages' to process the queue.
To ensure that the user receives immediate feedback, I’ll use preventDefault to store the message and clear the form without directly fetching from the main script. Since both the main script and the service worker can access the same IndexedDB database, I’ll consider creating an 'idb.js' helper library to perform simple CRUD operations, though I might implement these operations directly in both files to keep things straightforward.Designing the IndexedDB Structure
I’m aware that the code size is likely to be big, but that’s fine. Since we won’t have an actual backend, we can simulate sending data to a placeholder like https://jsonplaceholder.typicode.com/posts while needing to inform the user they must be offline for the queue. For background sync, we’ll send data to a placeholder API like https://example.com/api/messages.
I'll plan our project structure with a focus on offline caching and background synchronization, mentioning running a simple HTTP server, ensuring it's on HTTPS or localhost. To simplify code, I'll create a common db.js file for IndexedDB operations shared between main.js and the service worker, allowing for consistency and minimizing duplication.Creating PWA Files
I’m constructing the essential files for the PWA, including index.html, offline.html, manifest.json, main.js, db.js, and sw.js. For index.html, I'll set up a simple structure with a form for message submission.
The manifest.json needs to include basic information, and sw.js will manage caching and background sync. I'll incorporate IndexedDB functions in db.js for handling message storage in both main and service worker contexts. I'll ensure that these functions operate smoothly across different scopes and handle asynchronous operations with promises.Designing IDB Functions and PWA Structure
I’m identifying edge cases where, instead of clearing the store entirely, I may only want to remove successfully sent messages. I could send messages sequentially and clear them from IndexedDB once confirmed sent. This means I’ll need a deleteMessage function to remove individual messages by their ID.
In db.js, I'll organize functions for opening the database, saving messages, retrieving all messages, and deleting them. When processing messages for sending, I’ll iterate through and delete each one after a successful fetch call. I'll need to ensure everything is set correctly in the service worker for smooth operation. Below is a minimal, end‑to‑end example of a PWA that:
Installs as an app (manifest + service worker)
Caches assets for offline use
Queues form submissions while offline and sends them later using Background Sync
You can copy this structure into a project directory and run it on https:// or http://localhost.
// sw.js
// Import IndexedDB helpers
importScripts('/db.js');
const CACHE_NAME = 'pwa-demo-static-v1';
const OFFLINE_URL = '/offline.html';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/offline.html',
'/styles.css',
'/main.js',
'/db.js',
'/manifest.json',
// add icons, fonts, etc. here
];
// --- Install: cache app shell ---
self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(ASSETS_TO_CACHE))
.then(() => self.skipWaiting())
);
});
// --- Activate: cleanup old caches ---
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
)
)
.then(() => self.clients.claim())
);
});
// --- Fetch: offline caching strategy ---
self.addEventListener('fetch', (event) => {
const request = event.request;
// For navigations (page loads), try network, fall back to offline page
if (request.mode === 'navigate') {
event.respondWith(
fetch(request).catch(() => caches.match(OFFLINE_URL))
);
return;
}
// For other requests: cache-first, then network
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request)
.then((response) => {
// Optionally cache new resources
const responseClone = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseClone);
});
return response;
})
.catch(() => {
// For failed non-navigation requests, just fail silently
// or provide additional fallbacks if needed.
});
})
);
});
// --- Background Sync: flush outbox when back online ---
self.addEventListener('sync', (event) => {
if (event.tag === 'sync-messages') {
event.waitUntil(sendOutbox());
}
});
async function sendOutbox() {
try {
const messages = await getAllMessages();
if (!messages.length) {
console.log('Outbox is empty, nothing to sync.');
return;
}
console.log(`Syncing ${messages.length} message(s) from outbox...`);
for (const item of messages) {
const payload = item.data;
// Replace with your real API endpoint
const res = await fetch('/api/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) {
throw new Error(`Server responded with ${res.status}`);
}
// On success, remove the item from the queue
await deleteMessage(item.id);
}
console.log('All queued messages have been synced.');
} catch (err) {
console.error('Background sync failed; will retry next time:', err);
// Throw to signal failure so browser may retry later
throw err;
}
}
9. Running and testing
Serve over HTTP(S)
From the project root, for example:
bash
# Python 3
python -m http.server 8080
# or with Node
npx serve .
Then open http://localhost:8080 in a Chromium-based browser.
Install the PWA
In Chrome, you should see an install prompt or an install icon in the URL bar if criteria are met (valid manifest + service worker + HTTPS/localhost).
Test offline caching
Load the app once online.
Turn on “Offline” in DevTools → Network or disable your network.
Reload the page.
The app shell should still load from cache; navigations fall back to offline.html.
Test background sync
Open DevTools → Application → Service Workers.
Go offline.
Submit several messages.
Go back online.
If Background Sync is supported (Chrome/Edge/Android), the sync event will fire and queued messages will be sent to /api/messages.
Note: Safari does not support Background Sync at time of writing, so this part won’t fire there.
If you tell me your tech stack (vanilla, React, Vue, etc.), I can adapt this into a framework-specific setup or convert it to use Workbox for more advanced caching strategies.