Web App Manifests & Service Worker Caching Strategies
An authoritative reference manual on manifest.json metadata, Service Worker event lifecycles, offline cache storage, and caching strategies.
The technical foundation of a Progressive Web Application consists of two core components: the Web App Manifest configuration and the Service Worker background proxy. This chapter examines JSON configurations, lifecycle events, and caching algorithms.
6.1. Web App Manifest Specification (`manifest.json`)
Definition: The Web App Manifest is a JSON file providing metadata that informs mobile and desktop operating systems how to display the web application when installed on the user's device.
Core Working Principles:
- `name` & `short_name`: Specifies full app name for install prompts and short name for below the mobile home screen icon.
- `display: standalone`: Removes browser address bars, tabs, and OS chrome, providing a true native application UI.
- `icons` Array: Provides multiple image resolutions (192x192, 512x512) for splash screens and home screen launcher icons.
{
"name": "Shafi Institute Study Portal",
"short_name": "StudyPortal",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#0f172a",
"theme_color": "#6366f1",
"icons": [
{
"src": "/icons/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icons/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
5-Marks Exam Scoring Points
- manifest.json provides app name, icons, theme colors, and display configuration to the host OS.
- display: standalone hides browser URL navigation bars to deliver a native look and feel.
- Linked in the document head: <link rel='manifest' href='manifest.json'>.
6.2. Service Worker Lifecycle & Offline Caching Strategies
Definition: A Service Worker is an event-driven background JavaScript worker executing independently of web pages, serving as a network proxy to manage offline caches and background synchronization.
Core Working Principles:
- Lifecycle Events: **Registration** (registers sw.js) $\rightarrow$ **Installation** (precaches static assets) $\rightarrow$ **Activation** (purges outdated caches) $\rightarrow$ **Fetch Interception** (proxies requests).
- Cache Storage API: Persistent key-value storage engine holding HTTP `Request` and `Response` object pairs.
- Caching Strategies: Patterns governing data retrieval: **Cache-First** (fastest for static CSS/JS), **Network-First** (best for real-time APIs), and **Stale-While-Revalidate** (instant cache return + background refresh).
Imagine ordering food at home:
- Cache-First Strategy: The Butler checks your home pantry (Cache) first. If milk is in the pantry, he serves it instantly! He only walks to the supermarket (Network) if the pantry is empty.
- Stale-While-Revalidate: The Butler hands you the milk currently in the pantry instantly so you can drink right away, but simultaneously sends an assistant to the supermarket to restock fresh milk for next time!
graph TD
PageReq[Page Request: fetch event] --> SW{Service Worker Proxy}
subgraph Stale-While-Revalidate Strategy
SW -->|1. Check Cache Storage| CacheLookup{Cache Hit?}
CacheLookup -->|Yes: Return Instantly| ImmediateRes[Return Cached Response to Page]
SW -->|2. Parallel Network Fetch| NetFetch[Fetch Fresh Asset from Server]
NetFetch -->|3. Update Storage| UpdateCache[Cache Storage: Overwrite with Fresh Copy]
CacheLookup -->|No Cache| NetFetch
end
| Caching Strategy | Execution Mechanism | Optimal Asset Use Case |
|---|---|---|
| Cache-First (Cache Fallback Network) | Checks Cache; if missing, fetches from Network and updates Cache. | Static assets (Fonts, Icons, Compiled CSS/JS bundles) |
| Network-First (Network Fallback Cache) | Fetches fresh data from Network; if offline, falls back to Cache. | Dynamic API endpoints (User account balances, News feeds) |
| Stale-While-Revalidate 🏆 | Returns cached asset instantly while updating cache in background. | Avatars, textbook chapters, frequently viewed documentation |
const CACHE_NAME = 'study-portal-v1';
const ASSETS = ['/', '/index.html', '/style.css', '/app.js'];
// Pre-cache static assets during installation
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
});
// Intercept network requests with Stale-While-Revalidate
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => {
const networkFetch = fetch(event.request).then(response => {
return caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, response.clone());
return response;
});
});
return cached || networkFetch;
})
);
});
5-Marks Exam Scoring Points
- Service Workers operate on a separate thread, acting as event-driven network proxies.
- The install event precaches core shell assets; activate event purges outdated cache keys.
- Stale-While-Revalidate provides instant page loads while updating cached assets asynchronously.
✍️ Chapter 6 Reference Exercises & Review Problems
1. Registration: Browser registers `sw.js` and downloads the script.
2. Installation: Service worker triggers `install` event to precache application shell files.
3. Role of `event.waitUntil()`: Pre-caching files over the network takes time. `event.waitUntil()` extends the installation phase until the caching Promise resolves. If caching fails, installation aborts and the service worker is discarded.
- Cache-First: Checks Cache Storage first; fetches from network only if missing. Best for immutable static assets (CSS, JS libraries, Google Fonts) where speed is paramount.
- Network-First: Attempts to fetch fresh data over the network first; falls back to Cache only if offline. Best for real-time dynamic data (bank transactions, stock prices) where data freshness is critical.