Example of a Service Worker working offline
Example of a Service Worker working offline
One of the most important capabilities of Service Workers is making websites available even without internet. We enable offline mode by caching essential files and providing a fallback page when the network is unavailable.
Caching the fallback page in the install event
const CACHE_NAME = 'offline-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/offline.html',
'/styles.css',
'/main.js',
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(urlsToCache);
})
);
});
Using the fallback page in the fetch event
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(event.request).then(response => {
return response || caches.match('/offline.html');
});
})
);
});
In this example, if a network request fails (for example, when the user is offline), the browser will try to get the requested file from cache. If it's not in cache, it will show the offline.html
page.
This is very useful for providing a good user experience, especially during travel, with poor connection, or network issues.