Service Worker implementation: caching strategies and offline mode

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Service Worker implementation: caching strategies and offline mode
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

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

  1. Analytics: audit current Core Web Vitals, identify bottlenecks (LCP, CLS).
  2. Design: select strategies for each resource group, determine scope.
  3. Implementation: write Service Worker (manually or via Workbox), integrate with build system.
  4. Testing: verify in Chrome DevTools (Application > Service Workers), Lighthouse, WebPageTest.
  5. 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.

MDN Web Docs: Service Worker API

What happens when your website isn't available offline?

A news site loses 40% of returning readers when articles fail to load on the subway. A fintech dashboard becomes useless during a commute. PWA app development solves that by turning your website into an installable application that works without internet, sends push notifications, and loads instantly. One codebase replaces two native teams. Over 7 years we have delivered 30+ PWA projects for e-commerce, fintech, and enterprise portals — each with measurable business impact. Contact us for a free PWA readiness assessment — we will audit your current application and estimate the effort.

How does Service Worker manage network requests?

Service Worker — a JavaScript proxy running in a separate thread — intercepts every HTTP request and decides the response source: cache, network, or a mix. Three core strategies solve most real-world scenarios.

Caching strategy Typical assets Offline behavior
Cache First JS/CSS with content hash (e.g. main.a1b2c3.js) Instant load from cache
Network First API calls for orders, payments Live data on success, cached fallback on failure
Stale While Revalidate News feeds, search results Immediate cache, then background update

Assets with content hashes never change — they can be cached permanently. Stale While Revalidate gives instant response while keeping data fresh within seconds. Google's Workbox automates versioning and cache invalidation; without it a correct Service Worker would require 300+ lines of code. Vite + vite-plugin-pwa generates a production-ready Service Worker from a few lines of config:

import { VitePWA } from 'vite-plugin-pwa';
export default {
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico'],
      manifest: { /* name, icons, start_url, display */ },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
        runtimeCaching: [
          { urlPattern: /^https?:\/\/api\./,
            handler: 'NetworkFirst',
            options: { cacheName: 'api-cache' }
          }
        ]
      }
    })
  ];
};

How is offline mode implemented in practice?

"Works offline" means different things for a news site vs. a CRM. Three typical scenarios:

  • Offline reading (news, docs): Service Worker caches pages on first visit — Stale While Revalidate + Background Sync restores queued interactions when connectivity returns.
  • Offline editing (notes, tasks): IndexedDB stores local data, Background Sync API queues operations and pushes them automatically even if the browser tab is closed. Limitation: Background Sync is supported only in Chromium (~84% of desktop and mobile users).
  • Offline forms: user taps 'Send' without internet — data is preserved in IndexedDB and submitted when the connection is restored. Critical for medical and insurance claim forms.

One commonly underestimated problem: sync conflicts. If user A edits a record offline and user B changes it online, a resolution strategy (last-write-wins, three-way merge, or showing a conflict UI) must be designed upfront. We always address these scenarios during the architecture phase.

Common pitfalls we see in practice: lack of fallback UI (users see a white screen), wrong cache strategy for user-specific data (using Cache First for authenticated API calls), ignoring Service Worker scope (worker placed too deep), and skipping precache validation. Workbox automates cache versioning to avoid expired assets.

How do Web Push notifications work?

Web Push delivers messages through the browser's Push Service (FCM for Chrome/Edge, APNs for Safari). User grants permission → browser subscribes → you receive an endpoint and key → your backend sends a message via the web-push library (Node.js) or equivalent. VAPID keys are generated once, subscriptions stored in a database. iOS (16.4+) supports Web Push only for installed PWAs; Chrome/Firefox/Edge support it without installation. A/B testing send times and content is standard practice — irrelevant notifications cause churn rates above 30%.

Why choose PWA over native applications?

Building and maintaining native iOS and Android apps costs 2–3x more than a single PWA. One codebase, unified business logic, automatic updates — no App Store review delays. PWA lifts conversion by 36% on average (Google aggregated data). Web Push re-engages users at 4x the rate of email when messages are personalized. We have delivered PWA-solutions for high‑traffic e‑commerce platforms (12M monthly sessions) and enterprise fintech dashboards — each project included Core Web Vitals optimisation to pass Google's eligibility criteria. In our experience, PWA engagement metrics are 2–3x higher than mobile web alone, and push notification click-through rates are 7x better than email.

What does turnkey PWA development include?

Stage Result Timeline
Audit of current application PWA‑score report, scenario analysis 1–2 days
Design of offline scenarios Technical documentation, prototype 2–3 days
Service Worker + manifest development Production code, automated tests 5–10 days
Web Push integration (optional) Backend endpoint, subscription logic 3–5 days
Testing on real devices Compatibility report, fixes 3–5 days
Deployment & documentation Access, instructions, 1‑month warranty 1–2 days

Deliverables you receive

  • Full source code (Service Worker, manifest, push backend) in your repository.
  • Testing guide with Lighthouse audit results and real‑device reports.
  • Push notification dashboard or API endpoint for your marketing team.
  • Performance monitoring – instruction for checking Core Web Vitals after deployment.
  • 1 month of post‑launch support – bug fixes and minor adjustments.

What is App Shell architecture?

App Shell pre‑caches the minimal HTML, CSS and JavaScript needed to render the application chrome on first load. After the shell is cached, subsequent visits render instantly even on slow or offline connections. This technique is paired with dynamic content loading for a native‑like experience.

Process and timeline (from audit to go‑live)

  1. Audit: Lighthouse PWA score, offline scenario analysis.
  2. Prioritise valuable offline use cases (based on user behaviour data).
  3. Configure Service Worker via Workbox, implement manifest.
  4. Integrate Web Push (if required).
  5. Test on real devices – Chrome DevTools, Safari Web Inspector, Android Chrome.
  6. Deploy, hand over documentation, train the team.

Estimated timelines: basic PWA (manifest + Service Worker + static cache) – 1–2 weeks on top of existing application. Add Web Push – 1–2 weeks. Offline editing with IndexedDB and Background Sync – 3–6 weeks depending on data complexity. Cost is calculated individually after a free audit. On average, a PWA project costs 40–60% less than building two native apps – and you save recurring App Store fees. Get in touch for a free consultation – we will assess your project and propose the optimal implementation plan.

Further reading