Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Service Worker Pro

ASecurity

Control the network layer with Service Workers: caching strategies, offline support, background sync, and update flows. Use for offline-first web apps.

2 stars
0 votes
0 copies
0 views
Added 9/29/2026
ai-agentsgoshellapi

Works with

cliapi

Security Analysis

A100/100

Scanned 9/29/2026

$npx -y skills add aicodedecode/awesome-muse-skills --skill service-worker-pro --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Service Worker Pro?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Service Worker Pro
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/aicodedecode-service-worker-pro/badge)](https://www.skillsdirectory.com/skills/aicodedecode-service-worker-pro)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: service-worker-pro
description: Control the network layer with Service Workers: caching strategies, offline support, background sync, and update flows. Use for offline-first web apps.
category: web-development
---

# Service Worker Pro

A practical guide to Service Workers: the programmable network proxy in the browser — lifecycle, caching strategies, offline architectures, background sync, and the update flows that keep users on fresh code without breaking them.

## Overview

A Service Worker (SW) sits between your page and the network: it **intercepts requests** and decides — cache, network, or both. This enables offline support, instant repeat loads, and background sync. It's also the foundation of push notifications. The SW runs in its own thread with its own lifecycle (install → activate → fetch), independent of any page — which is both its power and its sharp edges (stale caches, update races).

## When to use

- Offline-capable web apps (see also pwa-patterns).
- Caching strategies for assets and API responses.
- Background sync for queued mutations.
- Push notification handling.
- Advanced prefetching/prerendering strategies.

## Core concepts

- **Lifecycle.** `install` (precache) → `activate` (cleanup old caches) → `fetch` (intercept). A new SW waits until all tabs using the old one close (`skipWaiting()` + `clients.claim()` to take over immediately — use deliberately).
- **Scope.** SW controls pages under its registration path. Register at root (`/sw.js`) for full-site control.
- **Cache API.** `caches.open('v1')` — programmatic cache storage, separate from HTTP cache. Version cache names; delete old versions on activate.
- **Strategies.** Cache-first (immutable assets), network-first (fresh data, cache fallback), stale-while-revalidate (fast + fresh eventually), network-only, cache-only. Match strategy to resource type.
- **Precache vs runtime.** Precache the app shell at install (known URLs); cache runtime requests as they happen (API responses, images).
- **Background Sync.** `sync.register('send-queue')` → SW retries when online — for queued mutations. One-shot; for periodic, Periodic Background Sync (limited support).
- **Update flow.** Byte-difference check on navigation → new SW installs → waits → activates. UX: notify "new version available" → user refreshes, or auto-`skipWaiting` for non-critical apps.

## Practical workflow

**1. Register.**
```js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(reg => {
    reg.addEventListener('updatefound', () => notifyUpdateAvailable());
  });
}
```

**2. Precache + strategies (vanilla).**
```js
const SHELL = 'shell-v3';
const PRECACHE = ['/', '/app.css', '/app.js', '/offline.html'];

self.addEventListener('install', (e) => {
  e.waitUntil(caches.open(SHELL).then(c => c.addAll(PRECACHE)).then(() => self.skipWaiting()));
});
self.addEventListener('activate', (e) => {
  e.waitUntil(caches.keys().then(keys =>
    Promise.all(keys.filter(k => k !== SHELL).map(k => caches.delete(k)))
  ).then(() => self.clients.claim()));
});
self.addEventListener('fetch', (e) => {
  const { request } = e;
  if (request.url.includes('/api/')) {
    e.respondWith(networkFirst(request, 'api-v1'));       // fresh data, offline fallback
  } else if (request.destination === 'image') {
    e.respondWith(cacheFirst(request, 'images-v1'));      // immutable-ish assets
  } else {
    e.respondWith(staleWhileRevalidate(request, SHELL));  // shell + pages
  }
});
```
(Or use Workbox — recommended over hand-rolling for production.)

**3. Offline fallback.** Navigation requests failing → serve cached `/offline.html`. API failing → serve cached response with a flag, or a structured offline error the app handles.

**4. Background sync for mutations.**
```js
// page: queue failed POSTs in IndexedDB, then
navigator.serviceWorker.ready.then(reg => reg.sync.register('outbox'));
// sw.js: self.addEventListener('sync', e => { if (e.tag === 'outbox') e.waitUntil(flushOutbox()); });
```

**5. Update UX.** `updatefound` → show "Update available — refresh" snackbar → on click, `registration.waiting.postMessage({ type: 'SKIP_WAITING' })` → `controllerchange` → `location.reload()`.

## Common pitfalls

- **Caching the SW file itself.** If `/sw.js` is cached with a long TTL, updates never arrive. Serve it `Cache-Control: no-cache` (revalidate every time).
- **Over-aggressive precaching.** Precaching everything = slow install, wasted bandwidth. Precache the shell; runtime-cache the rest.
- **Stale-forever bugs.** Cache-first on HTML/API without versioning = users stuck on ancient content. Version caches; prefer SWR/network-first for HTML.
- **Update races.** `skipWaiting` mid-session can break in-flight app state (old page, new cached assets). For complex apps, prompt the user instead of forcing.
- **Opaque responses.** Cross-origin `no-cors` responses are opaque — cacheable but inscrutable (can't check status). Prefer CORS-enabled endpoints.
- **Quotas.** Cache + IndexedDB share origin storage (browser-managed, evictable). Don't treat it as infinite; handle `QuotaExceededError`.
- **Dev confusion.** SW caching during development = "my changes aren't showing". Unregister in dev, or use dev-only bypass. Chrome DevTools → Application → Service Workers → "Update on reload" + "Bypass for network".
- **Scope mistakes.** Registering `/app/sw.js` controls only `/app/*`. Root registration for site-wide control.
- **Untested offline.** "Works offline" claimed, never tested. DevTools offline mode + real airplane-mode tests on device.

Attribution

aicodedecodeaicodedecode
View sourceSee grades on GitHubMore from aicodedecode →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698621 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents →