A service worker that serves from cache makes repeat visits nearly instant. But a worker that sits in front of every request without a plan can add delay. Here is what to watch.
Startup cost
When the browser needs a worker that is not running, it has to start it: typically tens of milliseconds on desktop, more on slow phones. For a network-first navigation that cost is added before the request even starts.
Navigation preload fixes that. The browser starts the network request in parallel with starting the worker:
self.addEventListener('activate', (event) => {
event.waitUntil(self.registration.navigationPreload?.enable());
});
self.addEventListener('fetch', (event) => {
if (event.request.mode !== 'navigate') return;
event.respondWith((async () => {
const preload = await event.preloadResponse;
if (preload) return preload;
try { return await fetch(event.request); }
catch { return caches.match('/offline.html'); }
})());
});
Navigation preload is supported in Chrome, Edge, Firefox and Safari. The server receives a Service-Worker-Navigation-Preload: true header, which you can use to send a lighter response.
Do not handle what you do not need
An empty fetch handler, or one that just calls fetch(event.request), adds the startup cost for nothing. If you do not need to intercept a request type, return without calling respondWith and the browser handles it normally.
Static routing
The Service Worker Static Routing API (Chromium) lets you declare at install time that some paths should go straight to the network or the cache without starting the worker at all:
self.addEventListener('install', (event) => {
event.addRoutes?.([
{ condition: { urlPattern: '/api/*' }, source: 'network' },
{ condition: { urlPattern: '/assets/*' }, source: 'cache' },
]);
});
Streaming
For app-shell sites, you can stream a cached header immediately while the body comes from the network, using ReadableStream. The page starts rendering sooner. Workbox has a workbox-streams module for this.
Keep caches small
- Precache only what the app needs to start. Cache everything else at runtime.
- Limit runtime caches by entry count and age, as PWA.live does (80 pages, 120 assets). Workbox's
ExpirationPlugindoes this for you. - Do not cache video or large downloads without a reason; use Background Fetch.
Measure
Compare repeat-visit load times with and without the worker (DevTools: Application > Service workers > Bypass for network). In the field, the Navigation Timing entry workerStart shows when the worker started; responseStart - workerStart shows how long it took to answer.
Browser support
| Feature | Chrome / Edge desktop | Chrome Android | Safari iOS / iPadOS | Safari macOS | Firefox desktop | Firefox Android | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Navigation preload | Chrome / Edge desktop: Yes | Chrome Android: Yes | Safari iOS / iPadOS: Yes | Safari macOS: Yes | Firefox desktop: Yes | Firefox Android: Yes | Samsung Internet: Yes |