Service Workers con Claude Code
Aprenda sobre Service Workers usando Claude Code. Incluye consejos practicos y ejemplos de codigo.
Service Workerの役割
Service Workerはブラウザとネットワークの間に位置するプロキシで、オフライン対応・キャッシュ制御・プッシュ通知などを実現します。PWA(Progressive Web App)の中核技術ですが、ライフサイクルやキャッシュ戦略の理解が必要です。Claude Codeを使えば、目的に合ったService Workerを正しく実装できます。
Service Workerの登録
> Service Workerを登録するユーティリティを作って。
> 更新検知とユーザーへの通知も含めて。
export async function registerServiceWorker() {
if (!('serviceWorker' in navigator)) {
console.log('Service Worker非対応のブラウザです');
return;
}
try {
const registration = await navigator.serviceWorker.register('/sw.js', {
scope: '/',
});
// 更新の検知
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
if (!newWorker) return;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
// 新しいバージョンが利用可能
showUpdateNotification(registration);
}
});
});
console.log('Service Worker登録完了:', registration.scope);
} catch (error) {
console.error('Service Worker登録失敗:', error);
}
}
function showUpdateNotification(registration: ServiceWorkerRegistration) {
if (confirm('新しいバージョンが利用可能です。更新しますか?')) {
registration.waiting?.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
}
}
キャッシュ戦略の実装
> Cache First、Network First、Stale While Revalidateの3つのキャッシュ戦略を実装して。
// sw.js
const CACHE_NAME = 'app-cache-v1';
const STATIC_ASSETS = ['/', '/index.html', '/styles.css', '/app.js'];
// Cache static assets on install
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS))
);
});
// Cache First(静的アセット向け)
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
return response;
}
// Network First(API向け)
async function networkFirst(request) {
try {
const response = await fetch(request);
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
return response;
} catch {
const cached = await caches.match(request);
return cached || new Response('オフラインです', { status: 503 });
}
}
// Stale While Revalidate(ニュースフィード向け)
async function staleWhileRevalidate(request) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(request);
const fetchPromise = fetch(request).then((response) => {
cache.put(request, response.clone());
return response;
});
return cached || fetchPromise;
}
// Routing
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.destination === 'image' || url.pathname.match(/\.(css|js|woff2?)$/)) {
event.respondWith(cacheFirst(request));
} else if (url.pathname.startsWith('/api/')) {
event.respondWith(networkFirst(request));
} else {
event.respondWith(staleWhileRevalidate(request));
}
});
オフラインページ
// オフライン時のフォールバックページ
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request).catch(() => caches.match('/offline.html'))
);
}
});
バックグラウンド同期
// オフライン時にキューに入れ、オンライン復帰時に送信
self.addEventListener('sync', (event) => {
if (event.tag === 'sync-pending-data') {
event.waitUntil(syncPendingData());
}
});
async function syncPendingData() {
const db = await openDB('pending-requests');
const requests = await db.getAll('queue');
for (const req of requests) {
try {
await fetch(req.url, req.options);
await db.delete('queue', req.id);
} catch {
break; // まだオフラインなら中断
}
}
}
Summary
Claude Codeを使えば、キャッシュ戦略の選定からオフライン対応、バックグラウンド同期まで、Service Workerの活用を効率的に実装できます。PWA全般はProgressive Web App開発を、キャッシュ戦略の詳細はキャッシュ戦略を参照してください。
Service Workerの詳細はMDN Web Docs - Service Worker APIをご覧ください。
PDF gratuito: Hoja de trucos de Claude Code en 5 minutos
Solo deja tu correo y te enviaremos al instante la hoja de trucos en una página A4.
Cuidamos tus datos personales y nunca enviamos spam.
Sobre el autor
Masa
Ingeniero apasionado por Claude Code. Dirige claudecode-lab.com, un medio tecnológico en 10 idiomas con más de 2.000 páginas.
Artículos relacionados
7 plantillas de CLAUDE.md para Claude Code que puedes copiar en proyectos reales
Siete plantillas prácticas de CLAUDE.md para apps individuales, sitios de contenido, APIs, equipos y repos legacy, con errores que debes evitar.
Guia de Approval y Sandbox para Claude Code | Configuracion segura para el trabajo diario
Como dividir acciones de Claude Code en allow, ask, deny y sandbox con settings practicos, hooks y casos reales.
Guía completa para empezar con Claude Code 2026 | De cero a usarlo en tu trabajo real en 7 pasos
La guía definitiva para quienes usan Claude Code por primera vez. Desde la instalación hasta integrarlo en tu flujo de desarrollo real — con todos los tropiezos que Masa tuvo al comenzar.