/web-pwa-service-workers
Service Worker lifecycle, caching strategies, offline patterns, update handling, precaching, runtime caching
$ npx -y skills add agents-inc/skills --skill web-pwa-service-workers --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/web-pwa-service-workers
Context preview
The summary Claude sees to decide when to auto-load this skill.
Service Worker lifecycle, caching strategies, offline patterns, update handling, precaching, runtime caching
SKILL.md
web-pwa-service-workers.SKILL.mdname: web-pwa-service-workers
description: Service Worker lifecycle, caching strategies, offline patterns, update handling, precaching, runtime caching
Service Worker Patterns
> **Quick Guide:** Use Service Workers for offline-first applications with sophisticated caching. Implement cache-first for static assets, network-first for HTML, and stale-while-revalidate for API data. Always handle the install/activate/fetch lifecycle properly, version your caches, and provide user control over updates. Clone responses before caching (body can only be consumed once).
---
<critical_requirements>
CRITICAL: Before Using This Skill
> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)
**(You MUST call `event.waitUntil()` in install and activate handlers to signal completion)**
**(You MUST version your caches and clean up old versions during activation)**
**(You MUST clone responses before caching - `cache.put(request, response.clone())` - response body can only be consumed once)**
**(You MUST implement proper update detection and give users control over when updates apply)**
**(You MUST handle all fetch failures with appropriate offline fallbacks)**
</critical_requirements>
---
**Auto-detection:** Service Worker, serviceWorker, sw.js, sw.ts, navigator.serviceWorker, caches, Cache API, CacheStorage, skipWaiting, clients.claim, precache, offline-first, PWA
**When to use:**
- Building Progressive Web Apps (PWAs) with offline support
- Implementing sophisticated caching strategies beyond browser defaults
- Providing offline fallback pages or cached content
- Controlling how network requests are handled and cached
**When NOT to use:**
- Simple websites without offline requirements
- When browser HTTP caching is sufficient
- For real-time data that must always be fresh (use network-only)
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Registration, lifecycle template, caching strategy implementations, types
- [examples/caching.md](examples/caching.md) - Advanced caching (expiration, selective API, storage cleanup, navigation preload)
- [examples/updates.md](examples/updates.md) - Version tracking, update strategies (aggressive, deferred, idle, rollout, migration)
- [reference.md](reference.md) - Decision frameworks, anti-patterns, lifecycle reference, checklists
---
<philosophy>
Philosophy
Service Workers are **programmable network proxies** that run in a separate thread, intercepting requests between your application and the network. They enable offline functionality, sophisticated caching, and background operations.
**The Service Worker lifecycle is designed for safety:**
1. **Install Phase:** Download and cache critical assets. The worker is "waiting" until installation completes. 2. **Waiting Phase:** New workers wait for all tabs using the old worker to close, preventing version conflicts. 3. **Activate Phase:** Old caches are cleaned up, and the worker takes control. 4. **Fetch Phase:** The active worker intercepts all network requests within its scope.
Registration → Download → Install → Waiting → Activate → Fetch
↓ ↓
(skipWaiting) (claim)**Core Principles:**
1. **Safety First:** The lifecycle prevents running multiple versions simultaneously, which could corrupt state. 2. **User Control:** Users should decide when updates apply, not be surprised by sudden behavior changes mid-session. 3. **Graceful Degradation:** Always provide fallbacks when network and cache both fail. 4. **Cache Versioning:** Version your caches to enable clean upgrades and prevent unbounded growth.
</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Service Worker Registration
Register from your main application with feature detection, update checking, and user-controlled updates.
const SW_PATH = "/sw.js";
const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
const registration = await navigator.serviceWorker.register(SW_PATH, {
scope: "/",
updateViaCache: "none", // Always check server for updates
});
// Periodic update checks
setInterval(() => registration.update(), UPDATE_CHECK_INTERVAL_MS);
// Track waiting worker for user-controlled updates
registration.addEventListener("updatefound", () => {
const installing = registration.installing;
installing?.addEventListener("statechange", () => {
if (
installing.state === "installed" &&
navigator.serviceWorker.controller
) {
// New version waiting - notify user
}
});
});See [examples/core.md](examples/core.md) Pattern 1 for complete registration with update tracking and reload handling.
---
Pattern 2: Lifecycle Handlers (Install / Activate / Message)
The three essential lifecycle event handlers: precache in install, cleanup in activate, user-controlled skipWaiting via message.
// Install - precache critical assets
self.addEventListener("install", (event: ExtendableEvent) => {
event.waitUntil(
caches.open(CACHES.static).then((cache) => cache.addAll(PRECACHE_URLS)),
);
// Do NOT call skipWaiting here - let user control updates
});
// Activate - cleanup old caches, claim clients
self.addEventListener("activate", (event: ExtendableEvent) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names
.filter((n) => !currentCaches.includes(n))
.map((n) => caches.delete(n)),
),
)
.then(() => self.clients.claim()),
);
});
// Message - user-controlled skipWaiting
self.addEventListener("message", (event: ExtendableMessageEvent) => {
if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});See [examples/core.md](examples/core.md) Pattern 2 for complete template with constants and type safety.
---
Pattern 3: Caching Strategies
Four strategies to match content types:
Read more
name: web-pwa-service-workers description: Service Worker lifecycle, caching strategies, offline patterns, update handling, precaching, runtime caching
Service Worker Patterns
> **Quick Guide:** Use Service Workers for offline-first applications with sophisticated caching. Implement cache-first for static assets, network-first for HTML, and stale-while-revalidate for API data. Always handle the install/activate/fetch lifecycle properly, version your caches, and provide user control over updates. Clone responses before caching (body can only be consumed once).
---
<critical_requirements>
CRITICAL: Before Using This Skill
> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)
**(You MUST call `event.waitUntil()` in install and activate handlers to signal completion)**
**(You MUST version your caches and clean up old versions during activation)**
**(You MUST clone responses before caching - `cache.put(request, response.clone())` - response body can only be consumed once)**
**(You MUST implement proper update detection and give users control over when updates apply)**
**(You MUST handle all fetch failures with appropriate offline fallbacks)**
</critical_requirements>
---
**Auto-detection:** Service Worker, serviceWorker, sw.js, sw.ts, navigator.serviceWorker, caches, Cache API, CacheStorage, skipWaiting, clients.claim, precache, offline-first, PWA
**When to use:**
- Building Progressive Web Apps (PWAs) with offline support
- Implementing sophisticated caching strategies beyond browser defaults
- Providing offline fallback pages or cached content
- Controlling how network requests are handled and cached
**When NOT to use:**
- Simple websites without offline requirements
- When browser HTTP caching is sufficient
- For real-time data that must always be fresh (use network-only)
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Registration, lifecycle template, caching strategy implementations, types
- [examples/caching.md](examples/caching.md) - Advanced caching (expiration, selective API, storage cleanup, navigation preload)
- [examples/updates.md](examples/updates.md) - Version tracking, update strategies (aggressive, deferred, idle, rollout, migration)
- [reference.md](reference.md) - Decision frameworks, anti-patterns, lifecycle reference, checklists
---
<philosophy>
Philosophy
Service Workers are **programmable network proxies** that run in a separate thread, intercepting requests between your application and the network. They enable offline functionality, sophisticated caching, and background operations.
**The Service Worker lifecycle is designed for safety:**
1. **Install Phase:** Download and cache critical assets. The worker is "waiting" until installation completes. 2. **Waiting Phase:** New workers wait for all tabs using the old worker to close, preventing version conflicts. 3. **Activate Phase:** Old caches are cleaned up, and the worker takes control. 4. **Fetch Phase:** The active worker intercepts all network requests within its scope.
Registration → Download → Install → Waiting → Activate → Fetch
↓ ↓
(skipWaiting) (claim)**Core Principles:**
1. **Safety First:** The lifecycle prevents running multiple versions simultaneously, which could corrupt state. 2. **User Control:** Users should decide when updates apply, not be surprised by sudden behavior changes mid-session. 3. **Graceful Degradation:** Always provide fallbacks when network and cache both fail. 4. **Cache Versioning:** Version your caches to enable clean upgrades and prevent unbounded growth.
</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Service Worker Registration
Register from your main application with feature detection, update checking, and user-controlled updates.
const SW_PATH = "/sw.js";
const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
const registration = await navigator.serviceWorker.register(SW_PATH, {
scope: "/",
updateViaCache: "none", // Always check server for updates
});
// Periodic update checks
setInterval(() => registration.update(), UPDATE_CHECK_INTERVAL_MS);
// Track waiting worker for user-controlled updates
registration.addEventListener("updatefound", () => {
const installing = registration.installing;
installing?.addEventListener("statechange", () => {
if (
installing.state === "installed" &&
navigator.serviceWorker.controller
) {
// New version waiting - notify user
}
});
});See [examples/core.md](examples/core.md) Pattern 1 for complete registration with update tracking and reload handling.
---
Pattern 2: Lifecycle Handlers (Install / Activate / Message)
The three essential lifecycle event handlers: precache in install, cleanup in activate, user-controlled skipWaiting via message.
// Install - precache critical assets
self.addEventListener("install", (event: ExtendableEvent) => {
event.waitUntil(
caches.open(CACHES.static).then((cache) => cache.addAll(PRECACHE_URLS)),
);
// Do NOT call skipWaiting here - let user control updates
});
// Activate - cleanup old caches, claim clients
self.addEventListener("activate", (event: ExtendableEvent) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names
.filter((n) => !currentCaches.includes(n))
.map((n) => caches.delete(n)),
),
)
.then(() => self.clients.claim()),
);
});
// Message - user-controlled skipWaiting
self.addEventListener("message", (event: ExtendableMessageEvent) => {
if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});See [examples/core.md](examples/core.md) Pattern 2 for complete template with constants and type safety.
---
Pattern 3: Caching Strategies
Four strategies to match content types:
Showing the first part of this file.
The official skills marketplace for Agents Inc. 150+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?
Repo: agents-inc/skills
Other skills on agents-inc-skills.
- /ai-infrastructure-huggingface-inference
Hugging Face Inference SDK patterns for TypeScript/Node.js — InferenceClient setup, chat completion, text generation, streaming, embeddings, image generation, audio transcription, translation, summarization, and Inference Endpoints
Open skill - /ai-infrastructure-litellm
LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking, virtual keys, and production deployment
Open skill - /ai-infrastructure-modal
Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client patterns
Open skill - /ai-infrastructure-ollama
Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output, model management, and OpenAI-compatible endpoint
Open skill - /ai-infrastructure-replicate
Replicate SDK patterns for TypeScript/Node.js -- client setup, predictions, streaming, webhooks, file handling, model versioning, deployments, and training
Open skill - /ai-infrastructure-together-ai
Together AI SDK patterns for TypeScript — client setup, chat completions, streaming, structured output, function calling, embeddings, image generation, fine-tuning, and OpenAI-compatible endpoints
Open skill

