JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext

Learn the concept

Caching Strategies

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 cachingJavaScript
// 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))
      );
    })
  );
});

Real-World Applications

Use Cases

Building a Progressive Web App (PWA) that needs to function reliably offline

Using a service worker with a 'Cache First' strategy for static assets and an 'Offline-first' approach for application data, ensuring users can access core functionality even without a network connection.

Optimizing a news website or blog to provide a fast loading experience for repeat visitors

Implementing a 'Stale While Revalidate' caching strategy for article content, where users instantly see cached content, and the service worker fetches fresh content in the background for future visits.

Handling complex asset caching for a large-scale e-commerce platform

Leveraging Workbox to manage different caching strategies for various asset types (images, CSS, JavaScript, API responses), ensuring optimal performance, cache expiry, and efficient updates for dynamic product catalogs.

Mini Projects

Offline-First To-Do List PWA

intermediate

Develop a simple To-Do list application that registers a service worker to cache its HTML, CSS, and JavaScript, allowing it to be fully functional offline.

Dynamic Content Caching with Stale-While-Revalidate

intermediate

Build a small application that fetches data from an API and uses a service worker with the 'Stale While Revalidate' strategy to cache the API responses, demonstrating instant loading of stale data and background updates.

Industry Examples

Starbucks PWA

Starbucks' Progressive Web App uses service workers extensively to provide an app-like experience on the web. It caches menus, stores, and order information, allowing users to browse and even place orders (which syncs when online) while offline.

Google Maps

Google Maps utilizes service workers to offer offline map access and improve loading times. When a user views an area, map tiles and routing data can be cached, making subsequent access faster and enabling navigation without an active internet connection.

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?
PrevNext