When loading a site, every extra request to the server increases LCP. Without a Service Worker, resources are fetched from the network on every navigation, which is especially critical for mobile users with unstable connections. We solve this problem by implementing a background script that intercepts requests. Proper configuration of caching strategies can reduce LCP by 40–60% and TTFB by 3–5 times. Our experience shows that a well-tuned Service Worker increases conversion by 10–20% and cuts server load in half.
A recent case from our practice: a Next.js e-commerce site had an LCP of 4.2s instead of the 2.5s norm. After setting up the SW with a Network First strategy for pages and Cache First for static assets, LCP dropped to 1.8s and conversion increased by 15%. Over 6 years of work, we have implemented more than 80 projects with PWA, guaranteeing at least a 30% improvement in Core Web Vitals.
In this article, we'll break down how to implement caching properly so that users receive content instantly even when the network goes down. You'll learn which strategies to choose for different resource types and how to avoid typical mistakes.
What problems does a Service Worker solve?
A Service Worker eliminates several typical bottlenecks:
- Slow repeat visits: without a cache, all resources are re-requested. The SW returns them from cache instantly.
- Lack of offline access: when the network drops, the user sees a blank page. The SW can show a cached version.
- High TTFB: if API requests are not cached, every page render waits for a server response. The SW can respond from cache while updating data in the background.
- Hydration mismatch: with SSR, mismatches between server and client HTML. Caching static assets reduces hydration time.
Caching strategies: comparison
The main strategies are Cache First, Network First, Stale While Revalidate. The choice depends on the resource type and required freshness.
| Strategy | Application | Load time (ideal) | Resource volatility | Staleness risk |
|---|---|---|---|---|
| Cache First | Static assets (CSS, JS, fonts) | 0–50 ms (from cache) | None | Low if files are versioned |
| Network First | HTML pages, API | 200–500 ms (network) or 0 (offline) | Medium | Low, cache updates after each success |
| Stale While Revalidate | Images, products | 0 (cache) + 100 ms (background) | Low | Moderate, serves stale until update |
Cache First delivers from cache 10x faster than Network First for static assets. The first strategy is suitable for immutable files, the second for pages that must always be fresh, the third for resources where a stale version is acceptable for 1–2 seconds.
How we do it: case study
We work with React, Next.js, Vite. For production, we use the Workbox library — it eliminates manual caching and provides ready-made handlers. Example configuration with vite-plugin-pwa:
// vite.config.ts
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/api\.example\.ru/,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
networkTimeoutSeconds: 3,
expiration: {
maxEntries: 50,
maxAgeSeconds: 300,
},
},
},
{
urlPattern: /\.(?:webp|avif|jpg|png|svg)$/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'images-cache',
expiration: {
maxEntries: 200,
maxAgeSeconds: 30 * 24 * 60 * 60,
},
},
},
],
},
}),
],
});
Registration example
// src/service-worker-registration.ts
export function registerServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then(registration => {
console.log('SW registered:', registration.scope);
setInterval(() => registration.update(), 60 * 60 * 1000);
})
.catch(err => console.error('SW registration failed:', err));
});
}
}
Why is it important to cache API requests?
API requests are a common cause of high TTFB. If responses are not cached, each page navigation triggers a new request. A Network First strategy with a short cache lifetime (e.g., 5 minutes) speeds up repeat views. In case of network failure, the user will at least get cached data instead of an error. API response time can be up to 500 ms, while caching reduces it to 0–50 ms.
How to update the cache without losing users?
When updating a Service Worker, it is important to properly manage cache versions. In the activate event, we delete old caches, keeping only the current one. To notify the user about a new SW, we use the updatefound event and show an "Update" button:
navigator.serviceWorker.ready.then(registration => {
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing!;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
showUpdateNotification(() => {
newWorker.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
});
}
});
});
});
Process of work
- Analytics: audit current Core Web Vitals, identify bottlenecks (LCP, CLS).
- Design: select strategies for each resource group, determine scope.
- Implementation: write Service Worker (manually or via Workbox), integrate with build system.
- Testing: verify in Chrome DevTools (Application > Service Workers), Lighthouse, WebPageTest.
- Deployment: phased rollout, error monitoring.
Estimated timelines
Basic setup takes 1 to 2 days. If custom logic is required (e.g., GraphQL caching), the timeline increases to 4–5 days. Cost is calculated individually — contact us for an estimate.
What is included
- Service Worker configuration with strategies for static assets, pages, and API.
- Workbox setup (if using Vite/Webpack).
- Update notification implementation.
- Offline page creation.
- Testing and profiling.
- Documentation on strategies and operations.
- Post-release support (2 weeks).
Typical mistakes in Service Worker implementation
| Mistake | Consequence | Solution |
|---|---|---|
| Incorrect scope | Service Worker does not intercept requests | Specify scope: '/' |
| No cleanup of old caches | Accumulation of versions, wasted traffic | Delete old caches in activate |
| Caching without versioning | User sees outdated data | Use Network First or short cache lifetime |
Contact us for a consultation on your project. Order Service Worker implementation to improve Core Web Vitals.







