JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
senior
caching

How do service workers improve performance and what caching strategies exist?

service-worker
caching
offline
workbox
pwa
Quick Answer

Service workers intercept network requests enabling offline support and advanced caching. Strategies include Cache First (fast, stale risk), Network First (fresh, slow), Stale While Revalidate (best UX), and Cache Only/Network Only for specific needs.

Detailed Explanation

Service Worker Capabilities:

  • Intercept network requests
  • Cache responses programmatically
  • Serve content offline
  • Background sync
  • Push notifications

Caching Strategies:

  1. Cache First: Check cache, fallback to network

    • Best for: Static assets, fonts
  2. Network First: Try network, fallback to cache

    • Best for: API requests, fresh data
  3. Stale While Revalidate: Serve cache, update in background

    • Best for: Balance speed + freshness
  4. Cache Only: Only from cache

    • Best for: Offline pages
  5. Network Only: Never cache

    • Best for: Analytics, real-time

Code Examples

Service worker registration and basic caching
// Register service worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(registration => {
      console.log('SW registered:', registration.scope);
    })
    .catch(error => {
      console.log('SW registration failed:', error);
    });
}

// sw.js - Service Worker
const CACHE_NAME = 'app-cache-v1';
const ASSETS = [
  '/',
  '/index.html',
  '/styles.css',
  '/app.js',
  '/offline.html'
];

// Install - cache assets
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(ASSETS))
      .then(() => self.skipWaiting())
  );
});

// Activate - clean old caches
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames
          .filter(name => name !== CACHE_NAME)
          .map(name => caches.delete(name))
      );
    })
  );
});

Resources

Web.dev - Service Workers

article

Workbox

docs

Related Questions

What are the different types of caching for web applications?

junior
caching

What are Core Web Vitals and why do they matter?

junior
metrics
Previous
How do you identify and fix memory leaks in JavaScript applications?
Next
What is the Critical Rendering Path and how do you optimize it?