Progressive Web Apps: Mastering Offline Strategies with Service Workers
The mobile web in 2016 is often frustrating. "Lie-fi"-where the phone shows bars but the connection is dead-is the enemy of a good user experience. Google is pushing the Progressive Web App (PWA) concept to solve this, and the heart of the PWA is the Service Worker.
A Service Worker is a script that runs in the background, separate from your web page. It acts as a programmable network proxy.
The Lifecycle
Before we can use a Service Worker, we must register it.
// main.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('SW registered with scope:', registration.scope);
});
}
Strategy: Stale-While-Revalidate
One of the most powerful patterns is "Stale-While-Revalidate." It shows the user the cached content immediately (speed!) while simultaneously fetching the latest version from the network and updating the cache for the next visit.
// sw.js
const CACHE_NAME = 'v1-cache';
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function(response) {
// Start the network fetch
var fetchPromise = fetch(event.request).then(function(networkResponse) {
// Update the cache with the new version
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
// Return the cached response if we have it, otherwise wait for network
return response || fetchPromise;
});
})
);
});
Pre-caching the "App Shell"
To make the app feel like a native app, we should cache the "App Shell"-the core HTML, CSS, and JS-during the install event.
// sw.js
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll([
'/',
'/styles/main.css',
'/scripts/app.js',
'/images/logo.png'
]);
})
);
});
In 2016, we are finally breaking the dependency on a constant internet connection. If you build it right, your web app can be faster and more reliable than many native apps on the market.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development