Service Worker (sw.js):
We'll use a cache-first strategy for static assets and network-first for dynamic content.
However, note: for low-bandwidth, we might want to cache more aggressively.
We'll have:
- A cache for static assets (with a version)
- A cache for dynamic content (with a shorter expiration)
But for simplicity, we'll do:
- Cache static assets (CSS, JS, images) with a cache-first strategy.
- For HTML, we can do network-first but if network fails, use cache.
However, for low-bandwidth, we might want to avoid network requests as much as possible.
Alternatively, we can do:
- For static assets: cache first, then network (to update in background).
- For HTML: network first, then cache.
But note: the user might be on a very slow network, so we don't want to wait for network if we have a cached version.
Let's do:
- For static assets: cache first, and then update the cache in the background (using a stale-while-revalidate approach).
- For HTML: network first, but if network fails, use cache. And if we have a cached version, we can still update it in the background.
We'll have two caches: 'static-cache' and 'pages-cache'.
However, for simplicity in this example, we'll do one cache and use different strategies by request type.
But note: the same resource might be requested as a static asset (like an image) and as part of an HTML page.
Actually, we can separate by MIME type or by pattern.
Alternatively, we can have:
- static-cache: for all files that are not HTML (css, js, images, fonts)
- pages-cache: for HTML
We'll use:
- For static-cache: CacheFirst
- For pages-cache: NetworkFirst
But note: we want to show something even when offline, so for HTML we must have a cached version.
So, we can pre-cache the critical HTML pages (like the home page) during the service worker installation.
Let's code:
We'll define:
- CACHE_NAME: 'low-bandwidth-v1'
- We'll have a list of static assets to pre-cache.
In the install event, we'll cache the static assets.
Then in the fetch event, we'll:
- If the request is for a static asset (based on file extension or pattern), use cache first, then network.
- If the request is for HTML, use network first, then cache.
But note: we might have API calls that return JSON. We don't want to cache those with the same strategy.
We can:
- If the request is for an API (ends with /api/), then do network only, but if offline, we might want to serve cached data?
That depends on the app. For low-bandwidth, we might want to cache API responses too.
However, let's stick to static assets and pages for now.
We'll define:
const STATIC_ASSETS = [
'/',
'/index.html',
'/styles.css',
'/app.js',
'/images/logo.png',
// ... other static assets
];
But note: we are going to pre-cache the static assets, so we don't need to list every image?
Actually, we can use a pattern or a list.
Alternatively, we can cache all requests that are not to the API and not HTML?
Let's do:
- Pre-cache the static assets (including HTML) during install? But then for HTML we want network first.
So, we'll pre-cache the static assets (css, js, images) but not the HTML?
Actually, we want to have the HTML cached for offline, but we want to update it when online.
So, we can pre-cache the HTML too, but then in the fetch for HTML, we do network first and if network fails, use cache.
But if we pre-cache the HTML, then the first load (when online) will get the cached version and then update in the background.
That's acceptable.
Steps:
install:
- cache all static assets (including HTML)
fetch:
- if request URL is in STATIC_ASSETS (which includes HTML) then use cache first, then network?
But for HTML we want network first.
Alternatively, we can split the static assets into two arrays:
const PRECACHE_ASSETS = [
'/styles.css',
'/app.js',
'/images/logo.png',
// ... other static assets except HTML
];
const HTML_PAGES = [
'/',
'/index.html',
'/about.html',
// ... other HTML pages
];
Then in fetch:
if (HTML_PAGES.includes(request.url)) {
// network first, then cache
} else if (PRECACHE_ASSETS.includes(request.url)) {
// cache first, then network
} else {
// network only? or maybe cache for other static assets that we encounter?
}
But note: we might have images that are not in PRECACHE_ASSETS. We want to cache them too, but we don't want to pre-cache all images.
We can do:
- For any request that is not an API and not HTML, do cache first, then network.
How to distinguish HTML? by the Accept header? or by the extension?
Let's do by extension: if the request ends with .html, then treat as HTML page.
But what about URLs without extension? We can assume they are HTML? Not safe.
Alternatively, we can check the MIME type in the response? But we don't have it until we fetch.
So, let's do:
- We'll have a list of HTML pages (without extensions) that we know are HTML.
But what about dynamic HTML? We are building a low-bandwidth app, so maybe we have server-side rendering?
Actually, we are building a mobile web app, so we might have a single page app. So the HTML is the same for all routes.
In that case, we only have one HTML file (index.html) and the rest are handled by the client.
So, we can do:
- For the initial HTML (the root and index.html), we do network first, then cache.
- For all other assets, cache first, then network.
But note: if the user is on a route like /about, the server returns the same index.html? Then we should treat /about as HTML?
Actually, in a SPA, the server returns the same HTML for every route. So we can't rely on the URL.
Therefore, we might have to rely on the Accept header? The browser sends Accept: text/html for HTML pages.
We can do:
const acceptHeader = request.headers.get('accept');
if (acceptHeader && acceptHeader.includes('text/html')) {
// network first, then cache for HTML
} else {
// cache first, then network for static assets
}
But note: some APIs might also return HTML? Unlikely.
Let's go with that.
However, we also have to handle:
- The case when we are offline and the user requests an HTML page: we must have it cached.
So, we must pre-cache the HTML pages (even though they are the same, we cache each route?).
Actually, we can pre-cache the root and index.html, but what about /about? The server returns the same index.html?
Then we can pre-cache the root and index.html, and then when the user goes to /about, the request for /about will be for HTML, but we don't have it in cache?
We can pre-cache all the routes? That's not efficient.
Alternatively, we can set up the server to return the same index.html for every route, and then we only need to cache one HTML file.
But the request URL is different. So we need to cache the same file under multiple URLs?
We can do:
In the service worker, when we get a request for /about, we can respond with the cached index.html?
How? We can check if the request is for HTML and then look for the cached index.html?
But note: the cache key is the request URL. So if we cached '/index.html' and the request is for '/about', they are different keys.
We can do:
- Pre-cache the root and index.html (so we have two entries?).
Actually, we can pre-cache the root (/) and index.html, and then for any HTML request that we don't have in cache, we try to fetch from network?
But when offline, we don't have network.
Alternatively, we can change the server to always return the same HTML file (index.html) for every route? Then we can pre-cache index.html and then for any HTML request, we respond with index.html.
But then the URL in the cache is index.html, but the request is for /about. So we need to map.
We can do in the fetch event:
if (request.mode === 'navigate' || (acceptHeader && acceptHeader.includes('text/html'))) {
// This is a navigation request for HTML.
// We can try to fetch from network, but if offline, we want to serve the cached index.html.
// But note: we might have cached the exact URL? For a SPA, we might not have cached every route.
// So, we can do:
// 1. Try to fetch the request (network)
// 2. If network fails, then try to get the cached index.html (by the URL of index.html) and return that.
// But we have to be careful: the cached index.html might be for a different route?
// Actually, the same index.html is used for every route. So we can cache it once.
// Alternatively, we can pre-cache the root and index.html, and then for any other HTML request, we return the cached index.html.
// Let's pre-cache the root and index.html, and then in the fetch:
if (cache.match(request)) {
// if we have the exact request in cache, use it (this would be the root or index.html for the root route)
return caches.match(request);
} else {
// For any other HTML request, we return the cached index.html (which is the SPA entry point)
return caches.match('/index.html');
}
}
But wait, what if the user requests a route that we haven't pre-cached? We are returning index.html, which is correct for a SPA.
So, we can pre-cache:
- The root (/) and index.html (they might be the same, but we cache both? Actually, they are the same resource? Not necessarily.)
Let's assume the server returns the same content for '/' and '/index.html'. Then we can cache only one of them?
But the request URL is different. So we need to cache both?
Alternatively, we can cache only the root and then when the request is for '/index.html', we redirect to '/'?
But that's not how the user navigates.
Actually, for a SPA, we don't have multiple HTML files. So we only have one HTML file. We can set the server to always return the same file for every route, and then we cache that file (say, index.html) and then for any navigation request, we return index.html.
So, we can pre-cache only:
'/index.html'
And then in the fetch:
if (request.mode === 'navigate' || (acceptHeader && acceptHeader.includes('text/html'))) {
// We are going to return the cached index.html for any HTML request.
return caches.match('/index.html').then(response => {
if (response) {
return response;
}
// If not in cache, then we try to fetch from network? But we are in the install phase, so it should be cached.
return fetch(request);
});
}
But note: we are pre-caching '/index.html', so it should be there.
Alternatively, we can do:
In the install event, cache '/index.html' and other static assets.
Then in the fetch event for HTML, we always return the cached index.html.
This is for a SPA.
If we have multiple HTML pages, then we need to cache each one and then decide which one to return.
But for a low-bandwidth mobile app, we are likely building a SPA.
So, let's assume SPA.
Steps for service worker:
const CACHE_NAME = 'low-bandwidth-v1';
const PRECACHE_ASSETS = [
'/',
'/index.html',
'/styles.css',
'/app.js',
'/images/logo.png',
// ... other static assets
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(PRECACHE_ASSETS);
})
);
});
self.addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
// If the request is for the service worker script, skip.
if (url.pathname === '/sw.js') {
return;
}
// Check if it's a navigation request or HTML request.
const acceptHeader = request.headers.get('accept');
const isHTMLRequest = request.mode === 'navigate' || (acceptHeader && acceptHeader.includes('text/html'));
if (isHTMLRequest) {
// For HTML, we want to serve the cached index.html (for a SPA) and then update in the background.
event.respondWith(
caches.match('/index.html').then(cachedResponse => {
if (cachedResponse) {
// Kick off a fetch in the background to update the cache.
fetch(request).then(response => {
if (response && response.status === 200) {
caches.open(CACHE_NAME).then(cache => {
cache.put('/index.html', response);
});
}
}).catch(() => {
// Network failed, we already have the cached version.
});
return cachedResponse;
}
// If we don't have it in cache (shouldn't happen because we precached), then try network.
return fetch(request);
})
);
} else {
// For static assets, cache first, then network.
event.respondWith(
caches.match(request).then(cachedResponse => {
if (cachedResponse) {
// Also, we can update the cache in the background for static assets?
// But static assets are versioned, so we might not want to update them without a version change.
return cachedResponse;
}
return fetch(request).then(response => {
// Check if the response is valid and cache it.
if (response && response.status === 200) {
const responseToCache = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(request, responseToCache);
});
}
return response;
});
})
);
}
});
However, note: the above for static assets will cache every static asset that is requested, even if not in PRECACHE_ASSETS.
That's okay for a low-bandwidth app? We want to cache as much as possible.
But we have to be careful about storage limits.
Alternatively, we can only cache the PRECACHE_ASSETS and then for other static assets, do network only?
But we want to cache images that are loaded dynamically?
We can do:
- For static assets that are in PRECACHE_ASSETS, we have them pre-cached and then we can use cache first.
- For other static assets, we can do network first? But then we are not caching them.
Actually, we want to cache everything we can. So the above approach (cache first for non-HTML) is good.
But note: we are caching everything that is not HTML, including API calls?
We don't want to cache API calls because they are dynamic.
So, we need to exclude API calls.
Let's change:
const isAPIRequest = url.pathname.startsWith('/api/');
Then, if it's an API request, we do network only (and if offline, we might want to return cached data? but that's more complex).
For now, let's not cache API requests.
So:
if (isAPIRequest) {
event.respondWith(
fetch(request).catch(() => {
// If offline, we can return a fallback? Or maybe we have cached the response in IndexedDB?
// For now, return a simple offline response for API.
return new Response(JSON.stringify({ error: 'offline' }), {
status: 503,
headers: { 'Content-Type': 'application/json' }
});
})
);
}
But note: the above will try the network and if it fails, return the offline error.
Alternatively, we can do:
- For API requests, we can try to get from IndexedDB (if we have stored the response) and then update in the background?
That's more complex and might be out of scope for the basic plan.
So, let's stick to:
-
HTML: cache first (with a cached index.html) and then update in background? Actually, we are doing cache first for HTML?
In the above, for HTML we are:
- If we have cached index.html, return it and then update in background.
- But note: we are not checking if the request is for a specific HTML page? We are always returning index.html.
That's because we are a SPA.
-
Static assets (non-API, non-HTML): cache first, then network.
-
API: network only, and if fails, return offline error.