What Offline Support For Your Web App Really Means
And how to implement it in a rock-solid way
Jun 5, 2024
The greatest misconception around offline support for web apps is that it means your app should provide the exact same user experience when the app is totally offline as when the app is online.
This is false.
Users are rarely completely offline for a long time.
A far more common situation is that the user is on a flaky and/or slow connection that causes your web app to break.
Even when you’re on 5G, you can experience a bad or slow connection in certain areas or circumstances.
It is for those situations that your app should provide the best possible user experience.
That is what offline support means and it applies to all web apps.
I say this because I often hear people say that offline support “doesn’t apply” to their web app or “doesn’t make sense” for it. For example, if you have a chat app you may think offline support doesn’t make sense for it because you can’t chat with anyone while offline.
But what if a user of your chat app is on a slow and intermittent network and loads your app or navigates to another page inside it? If this network is slow this may take a long time and when the network is completely gone the user may end up with a white screen.
If you had added a Service Worker to your chat app that would cache all JavaScript, images, CSS, and other assets locally then your app wouldn’t need to fetch these anymore and the limited bandwidth of that bad connection could then be used for more important things. Your app would load and reload much faster and the user experience would be much better.
A bad connection can also cause scripts not to be loaded or requests to fail. This is what you should always try to prevent with good offline support and that’s why I say providing offline support makes sense for all web apps.
There is no reason to show that “You are not connected to the internet” screen when the user refreshes the page and there’s no network. Ever.
Here’s how you can use a Service Worker to implement rock-solid offline support for your web app.
Assets and routes
Assets are all files that are part of your web app like JavaScript, images, CSS, and other types of files that your app uses. These can all be cached locally on the user’s device so your app doesn’t need to make a network request for them but instead can serve them from the local cache.
It’s important to understand this is not the same as the browser’s cache. This cache will also store files but the browser will always try to fetch the HTML document you request and if that fails when you’re offline, it will simply show a page telling you that you’re offline.
For this reason, you also need to cache all routes of your app, as I’ll show later.
The assets of your app are cached in the handler for the install event of your Service Worker. Each Service Worker goes through a distinct lifecycle:
Install -> Waiting -> Activate
In the install phase, the Service Worker caches all its assets and routes using the Cache interface. While it's in this phase, it can't yet control the app so it needs to stay in this phase until all assets are cached and other needed work is done.
In the install phase, the Service Worker caches all its assets and routes using the Cache interface. While it's in this phase, it can't yet control the app so it needs to stay in this phase until all assets are cached and other needed work is done.
This is accomplished by passing a function that returns a Promise to the waitUntil() method of the install event:
// list of files to cache
const filesToCache = [
'/src/css/styles.css',
'/src/js/app.js',
'/src/img/logo.png',
...
];
const version = 123;
self.addEventListener('install', e => {
e.waitUntil(
caches.open(`web-app-cache-${version}`)
.then(cache => cache.addAll(
filesToCache.map(file => new Request(file, {cache: 'no-cache'}))
))
.catch(err => console.error('cache error', err));
)
});
Here we open the cache named web-app-cache-123 and loop through the files listed in the filesToCache array and add them to the cache with the addAll method of cache.
As shown here, it’s good practice to add a version number to the cache so you can have a new cache every time there’s a new version of your Service Worker installed.
To make sure that the file you want to cache is always fetched from the network and not some older version from the browser’s cache we create a new Request with the cache option set to no-cache to make sure we always get the latest version.
The Service Worker will stay in the install phase while the files are cached and only move to the waiting phase after all files are cached. If there's an error while caching, the Promise will reject, installing will fail and the Service Worker will be discarded.
If all is ok, the Service Worker will move to the waiting phase and stay there until the current Service Worker no longer controls any clients (windows or tabs) and then move to the activate phase.
In addition to assets, you may also need to cache routes to make sure these result in a response when the web app is offline.
If you have a URL like https://my-web-app.com/home you need to make sure the Service Worker can respond with an HTML document when this is requested while offline. You can do this by simply adding these routes to the URLs you want to cache:
// list of files and URLs to cache
const filesToCache = [
// files
'/src/css/styles.css',
'/src/js/app.js',
'/src/img/logo.png',
...
// routes
'/home',
'/contact',
...
];
This will make your Service Worker cache the full HTML document for these routes so they will also be available while your web app is offline.
Outgoing requests
For good offline support, you also need to handle the outgoing requests that your web app makes while offline. Your app may need to update data on a server and those updates would be lost if not handled properly.
You can use a Service Worker and Background Sync to store these requests that are made by the app while it’s offline and then send them when the app comes back online, like the outbox functionality of an email app.
To implement this, we can use Background Sync, which is an API that enables developers to defer tasks (in this case requests) when the app is offline and run them when the app is back online.
To make use of Background Sync, you need to request a sync request with the SyncManager which is available through ServiceWorkerRegistration.sync so you first need to register a Service Worker and then request a sync with a unique tag:
await navigator.serviceWorker.register('/service-worker.js');
const registration = await navigator.serviceWorker.ready;
await registration.sync.register('retry-request');
Worker, we now register an event handler for the sync event and check the tag to identify the correct sync event:
self.addEventListener('sync', (event) => {
if (event.tag === 'retry-request') {
event.waitUntil(retryRequests());
}
});
sync events that you can attach different functionality to.
We will now check inside the fetch handler of the Service Worker if the web app is offline and if the request needs to be stored. If this is the case, we store the request in IndexedDB and request a sync with the ‘retry-request’ tag. Since this is now done inside the Service Worker we will get the SyncManager object from self.registration.sync instead of registration.sync like in the previous example:
self.addEventListener('fetch', e => {
const {request} = e;
const {url} = request;
if(!self.navigator.onLine && isRequestToBeStored(url)) {
await storeRequest(request);
return false;
}
// respond from cache or network
e.respondWith(
caches.match(request, {ignoreVary: true, ignoreSearch: true})
.then(response => response ? response : fetch(e.request))
)
})
Note that the function isRequestToBeStored() can be implemented however you want, depending on what requests you want to store.
The implementation of storeRequest() could be something like this:
const storeRequest = async (request) => {
const serializedHeaders = serializeHeaders(headers);
// save request to IDB somehow
await saveToIndexedDB(request);
// register sync
if('sync' in registration) {
await registration.sync.register(`retry-request`);
}
};
Now when the app comes back online, the sync event handler will be invoked and the retryRequests() function will be called like you saw in one of the previous examples:
self.addEventListener('sync', (event) => {
if (event.tag === 'retry-request') {
event.waitUntil(retryRequests());
}
});
and then delete them from IndexedDB.
In browsers that don’t support Background Sync you can use the online event of window which fires when the app comes back online after being offline. Inside the event handler you could post a message to the Service Worker to notify it that any requests that were stored when offline can now be sent:
window.addEventListener('online', () => {
navigator.serviceWorker.controller.postMessage({type: 'retry-requests'});
});
When the Service Worker receives this message it can then execute the same functionality that it does when the sync event fires. This doesn't offer the same amount of control and granularity that Background Sync offers but is a good fallback.
Conclusion
Offline support makes sense for all web apps and following these steps, you can implement it in a rock-solid way.
It will drastically improve the performance and user-experience of your web app with relatively little effort and is supported in all modern browsers.