Service Workers and Progressive Web Apps: Concepts, Lifecycle, and Workbox Integration
This article explains the fundamentals of Progressive Web Apps (PWA), focusing on Service Workers—its architecture, usage restrictions, compatibility, lifecycle stages, practical code examples, and how to simplify implementation with the Workbox framework for offline caching and push notifications.
Author: Sylvia (company alias), front‑end engineer at Beike Rental Platform.
Two years ago, Progressive Web Apps (PWA) became a hot topic in front‑end development, aiming to provide native‑app‑like experiences. The author first learned about PWA in late 2017 and began serious study after iOS 11.3 added support.
PWA implementation relies on three core components:
manifest : defines app icon, title, splash screen, etc.
service worker : handles offline caching, updates, and deletion; supported in iOS Safari 11.3+.
push/notification : enables message push and receipt.
1 Service Worker Overview
Before discussing Service Workers (SW), the article reviews JavaScript's single‑threaded nature, which can cause UI blocking during long tasks. Asynchronous mechanisms like ajax and promise mitigate this, while web worker provides background threads without DOM access.
SW is a type of web worker that runs in the browser background, intercepts network requests, and can cache responses, offering its own scope and environment.
1.1 SW Usage Restrictions
Cannot directly manipulate window , document , or parent objects; can access location and navigator .
Scope limited to the directory of sw.js and its sub‑directories unless a custom scope is set during registration.
Must be served over HTTPS, though localhost is allowed for development.
1.2 SW Compatibility
Supported on mobile Chrome, iOS Safari 11.3+, and desktop browsers like Firefox, Chrome, and Opera.
1.3 Problems Service Workers Solve
Speed up repeat visits by serving cached assets.
Cache API responses for offline use, with update and deletion capabilities.
Persist data on the client via IndexedDB.
2 Lifecycle
The Service Worker lifecycle consists of five steps: registration, installation (success or failure), activation, running, and termination. Key events include install , activate , message , fetch , push , and async .
2.1 First Registration Process
if('serviceWorker' in navigator){
navigator.serviceWorker.register('./sw.js', {scope: '/'})
.then(reg => console.log('Registration successful'))
.catch(error => console.log('Registration failed'));
}else{
console.log('Current browser does not support SW');
}2.2 Subsequent Visits
When the page is revisited while the previous SW is still active, it remains in the activated state.
2.3 Service Script Updates
Each visit triggers a download of sw.js . If the script changes, a new SW is installed and enters the waiting state until all controlled pages are closed, after which the new SW activates. Developers can call installEvent.skipWaiting() to activate immediately.
3 Practical Use of Service Workers
3.1 Registration
// main.js (main thread)
if('serviceWorker' in navigator){
navigator.serviceWorker.register('./sw.js', {scope: '/'})
.then(reg => console.log('Registration successful'))
.catch(err => console.log('Registration failed'));
}else{
console.log('Current browser does not support SW');
}3.2 Installation
const CACHE_NAME = 'sylvia_cache';
let filesToCache = [
'/src/css/test.css',
'/src/js/test.js'
];
self.addEventListener('install', function(event){
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
cache.addAll(filesToCache);
})
);
});3.3 Activation
self.addEventListener('activate', event => {
console.log('Installation successful, now controlling pages');
var cacheDeletePromise = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(key !== CACHE_NAME){
return caches.delete(key);
}else{
return Promise.resolve();
}
}));
});
event.waitUntil(
Promise.all([cacheDeletePromise]).then(() => {
self.clients.claim();
})
);
});3.4 Running (Fetch Interception)
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(res => {
if(res){
return res;
}else{
return fetch(event.request);
}
})
);
});3.5 Termination
SW can be terminated via self.terminate() when not needed, to conserve resources.
4 Workbox Framework
Google’s Workbox library simplifies SW development with pre‑caching and routing strategies.
4.1 Usage
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.3/workbox-sw.js');
if(workbox){
console.log('your workbox is working now');
}else{
console.log('it can\'t work!');
}Key Workbox APIs:
workbox.precaching.precacheAndRoute([...]) – pre‑cache listed assets.
workbox.routing.registerRoute(matchFunction, handler) – define routing with strategies.
Common caching strategies:
staleWhileRevalidate – serve cached response while updating in background.
networkFirst – try network, fall back to cache.
cacheFirst – serve from cache, fetch if missing.
networkOnly – always fetch from network.
cacheOnly – always serve from cache.
workbox.routing.registerRoute('/src/index.js', workbox.strategies.staleWhileRevalidate());5 Summary
The article demonstrates how to implement a basic offline cache using Service Workers, covering registration, lifecycle, caching strategies, and the Workbox library for easier integration.
Use Cases
Caching static resources that change infrequently.
Providing offline access to essential data.
Enabling push notifications for multi‑page synchronization (e.g., email, chat).
When updating caches, either replace the SW file or change the cacheStorage name; the latter is recommended to avoid stale SW issues.
6 References
https://developer.mozilla.org/zh-CN/docs/Web/API/Service_Worker_API
https://www.jianshu.com/p/916a01670a23
https://developers.google.com/web/tools/workbox/
7 Demo
Demo URL (not supported in WeChat): https://sylvialee.github.io/serviceWorker/
Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.