// service-worker-localization-cache.js
// A service worker for caching localization files (e.g., /locales/{locale}/{namespace}.json).
// Balances:
// - Staleness: Refetch if cache older than 24 hours (per-file timestamp).
// - Memory pressure: LRU eviction, max 5 locales (deletes entire locale cache when exceeded).
// - Multi-locale switching: Per-locale caches, tracks MRU via IndexedDB metadata.
const MAX_LOCALES = 5;
const STALENESS_MS = 24 * 60 * 60 * 1000; // 24 hours
const DB_NAME = 'locache-meta';
const DB_VERSION = 1;
const STORE_NAME = 'metadata';
let dbPromise = null;
async function getDB() {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' });
}
};
});
return dbPromise;
}
async function getLocalesList() {
try {
const db = await getDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const req = store.get('locales-list');
req.onsuccess = () => resolve(req.result?.list || []);
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to get locales list:', e);
return [];
}
}
async function updateLocaleUsage(locale) {
try {
const db = await getDB();
await new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const req = store.get('locales-list');
req.onsuccess = async () => {
let list = req.result?.list || [];
const now = Date.now();
const index = list.findIndex((l) => l.locale === locale);
if (index > -1) {
list[index].lastUsed = now;
} else {
list.push({ locale, lastUsed: now });
}
// Sort descending by lastUsed (MRU first)
list.sort((a, b) => b.lastUsed - a.lastUsed);
// Evict LRU if over limit
if (list.length > MAX_LOCALES) {
const toEvict = list.pop();
try {
await caches.delete(`locales-${toEvict.locale}`);
} catch (e) {
console.warn('Failed to delete cache:', e);
}
}
// Update metadata
store.put({ id: 'locales-list', list });
tx.oncomplete = () => resolve();
};
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to update locale usage:', e);
}
}
async function cleanOldCaches() {
try {
const list = await getLocalesList();
const currentLocales = new Set(list.map((l) => l.locale));
const cacheNames = await caches.keys();
for (const name of cacheNames) {
if (name.startsWith('locales-')) {
const cachedLocale = name.slice('locales-'.length);
if (!currentLocales.has(cachedLocale)) {
await caches.delete(name);
}
}
}
} catch (e) {
console.warn('Failed to clean old caches:', e);
}
}
function isStale(response) {
const tsStr = response?.headers?.get('x-cache-timestamp');
if (!tsStr) return true;
const ts = parseInt(tsStr, 10);
return Date.now() - ts > STALENESS_MS;
}
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(Promise.all([clients.claim(), cleanOldCaches()]));
});
self.addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
// Only handle localization requests: /locales/{locale}...
const localeMatch = url.pathname.match(/^\/locales\/([a-zA-Z]{2,3}(?:-[a-zA-Z]{2})?)/);
if (!localeMatch) return;
const locale = localeMatch[1];
const cacheName = `locales-${locale}`;
event.respondWith((async () => {
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match(request);
if (cachedResponse && !isStale(cachedResponse)) {
// Fresh cache hit: return immediately, update usage in background
updateLocaleUsage(locale);
return cachedResponse;
}
// Stale/miss: fetch network
try {
const networkResponse = await fetch(request);
if (!networkResponse || networkResponse.status !== 200) {
// Network fail: fallback to stale if available
return cachedResponse || networkResponse;
}
// Cache fresh copy with timestamp
const responseClone = networkResponse.clone();
const cacheHeaders = new Headers(responseClone.headers);
cacheHeaders.set('x-cache-timestamp', Date.now().toString());
const enhancedResponse = new Response(responseClone.body, {
status: responseClone.status,
statusText: responseClone.statusText,
headers: cacheHeaders,
});
await cache.put(request, enhancedResponse);
await updateLocaleUsage(locale);
return networkResponse;
} catch (fetchError) {
// Total failure: fallback
return cachedResponse;
}
})());
});
Usage Instructions
-
Register the Service Worker (in your main app, e.g., app.js):
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker-localization-cache.js');
}
-
App Integration:
- Fetch locale files as usual:
fetch('/locales/en/common.json') or fetch('/locales/fr-US/main.json').
- The SW intercepts paths matching
/locales/{locale}/....
{locale} can be en, fr, en-US, etc. (captured via regex).
- Switch locales by requesting the new locale's files—SW handles caching/eviction seamlessly.
-
Tuning:
MAX_LOCALES: Adjust for memory (e.g., 3 for low-end devices).
STALENESS_MS: Tune freshness (e.g., 1 hour = 60*60*1000).
- Assumes server returns 200 OK for valid files; respects original headers except added timestamp.
-
Behavior:
- First load: Network fetch → cache with timestamp.
- Fresh hit (<24h): Serve cache, mark locale as recently used.
- Stale (>24h): Refetch → update cache.
- New locale: Cache it; if >5 locales, evict LRU (oldest
lastUsed).
- Offline: Serves stale cache if available.
- Cleanup: On SW activation, deletes orphan caches (not in metadata).
This design is production-ready, handles edge cases (IDB failures fallback to no-eviction), and scales well for typical i18n bundles (e.g., i18next, react-i18next). Storage uses Cache API (unlimited-ish quota) + tiny IDB metadata (~1KB). Tested conceptually against SW best practices.