Claude Code के साथ Service Worker Usage Guide
Claude Code का उपयोग करके service worker usage guide सीखें। Practical tips और code examples शामिल हैं।
Service Workerの役割
Service Workerはブラウザとnetworkのबीचに位置するproxyで、オフラインsupport・cache制御・プッシュ通知 आदिを実現し है।PWA(Progressive Web App)のमें核技術ですが、ライフサイクルやcache戦略の理解がज़रूरी है।Claude Code का उपयोग करके、目的に合ったService Workerを正しくimplementationでき है।
Service Workerの登録
> Service Workerを登録するutilityを作って。
> update検知とuserへの通知も含めて。
export async function registerServiceWorker() {
if (!('serviceWorker' in navigator)) {
console.log('Service Worker非supportのブラウザです');
return;
}
try {
const registration = await navigator.serviceWorker.register('/sw.js', {
scope: '/',
});
// updateの検知
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
if (!newWorker) return;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
// नयाversionが利用possible
showUpdateNotification(registration);
}
});
});
console.log('Service Worker登録完了:', registration.scope);
} catch (error) {
console.error('Service Worker登録失敗:', error);
}
}
function showUpdateNotification(registration: ServiceWorkerRegistration) {
if (confirm('नयाversionが利用possible है।updateしますか?')) {
registration.waiting?.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
}
}
cache戦略のimplementation
> Cache First、Network First、Stale While Revalidateのतीनのcache戦略をimplement करो。
// 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));
}
});
オフラインpage
// オフライン時のフォールバックpage
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request).catch(() => caches.match('/offline.html'))
);
}
});
バックグラウンドsync
// オフライン時にqueueに入れ、オンライン復帰時に送信
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 का उपयोग करके、cache戦略の選定 सेオフラインsupport、バックグラウンドsync तक、Service Workerのutilizationをefficientlyimplementationでき है।PWA全般はProgressive Web Appdevelopmentを、cache戦略के details के लिएcache戦略をदेखें。
Service Workerके details के लिएMDN Web Docs - Service Worker APIदेखें。
Related Posts
Claude Code से Productivity 3 गुना बढ़ाने की 10 Tips
Claude Code से ज़्यादा पाने की 10 practical tips जानें। Prompt strategies से workflow shortcuts तक, ये techniques आज से ही आपकी efficiency boost करेंगी।
Claude Code के साथ Canvas/WebGL Optimization
Claude Code का उपयोग करके Canvas/WebGL optimization के बारे में जानें। Practical tips और code examples शामिल हैं।
Claude Code के साथ Markdown Implementation
Claude Code का उपयोग करके markdown implementation सीखें। Practical tips और code examples शामिल हैं।