Frontend Development 9 min read

Master Service Worker Caching with Workbox 3: Strategies & Code Samples

This article explains the fundamentals of Service Workers, demonstrates common pitfalls with raw SW code, provides a complete SW implementation, introduces Workbox 3 to simplify caching, compares several caching strategies, and shares practical recommendations for optimal PWA performance.

Taobao Frontend Technology
Taobao Frontend Technology
Taobao Frontend Technology
Master Service Worker Caching with Workbox 3: Strategies & Code Samples

Why Service Workers Matter

Service Workers act as the brain of a PWA, intercepting all network requests for a site once registered. By listening to the

fetch

event you can return cached responses, fetch new data, or construct custom

Response

objects.

Problematic SW Example

<code>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

self.addEventListener('fetch', function(event) {
  event.respondWith(new Response('bad'));
});
</code>

This tiny SW forces every request to return the string "bad", illustrating how powerful and risky an SW can be.

A More Complete SW

<code>var cacheStorageKey = 'cachesName';
var cacheList = [
  // URLs to pre‑cache after installation
];

self.addEventListener('install', function(e) {
  e.waitUntil(
    caches.open(cacheStorageKey).then(function(cache) {
      return cache.addAll(cacheList);
    })
  );
});

self.addEventListener('activate', function(e) {
  var cacheDeletePromises = caches.keys().then(function(cacheNames) {
    return Promise.all(
      cacheNames.map(function(name) {
        if (name !== cacheStorageKey) {
          return caches.delete(name);
        } else {
          return Promise.resolve();
        }
      })
    );
  });
  e.waitUntil(Promise.all([cacheDeletePromises]));
});

self.addEventListener('fetch', function(e) {
  // Custom caching logic goes here
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});
</code>

The install and activate phases handle pre‑caching and old‑cache cleanup; the real complexity lies in the

fetch

handler, where different strategies are applied based on file type.

Introducing Workbox 3

Workbox is Google’s official PWA framework that abstracts the low‑level Service Worker API. It provides utilities for precaching and routing, letting you focus on strategy selection instead of boilerplate code.

<code>importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.3.0/workbox-sw.js');

workbox.precaching.precacheAndRoute([
  // List of assets to pre‑cache
]);

// HTML – Network First
workbox.routing.registerRoute(new RegExp('.*\.html'), workbox.strategies.networkFirst());

// JS & CSS – Stale‑While‑Revalidate
workbox.routing.registerRoute(new RegExp('.*\.(js|css)'), workbox.strategies.staleWhileRevalidate());

// Images – Cache First with custom cache name
workbox.routing.registerRoute(new RegExp('https://your\.img\.cdn\.com/'),
  workbox.strategies.cacheFirst({cacheName: 'example:img'}));
</code>

Workbox’s

strategies

object offers several ready‑made policies:

Stale‑While‑Revalidate

Cache First

Network First

Network Only

Cache Only

You can extend these strategies with plugins (e.g., expiration) and even combine them with custom

fetch

handling.

Practical Recommendations

HTML : Use

NetworkFirst

if you need offline support; otherwise

NetworkOnly

. Avoid other strategies for HTML.

CSS & JS : When served from a CDN, prefer

Stale‑While‑Revalidate

to keep pages fast while allowing updates. If assets are version‑hashed on your own domain,

CacheFirst

is safe.

Images : Use

CacheFirst

with an expiration policy; never use

CacheOnly

or

CacheFirst

for cross‑origin resources.

These guidelines are general; adjust based on your site’s specific needs.

Real‑World Impact

After deploying a Service Worker on the Taobao PC homepage and fine‑tuning caching strategies, average page download time dropped from 1.7 s to 1.4 s – an 18 % improvement.

Workbox can be loaded from Alibaba’s CDN as well:

<code>importScripts('https://g.alicdn.com/kg/workbox/3.3.0/workbox-sw.js');
workbox.setConfig({modulePathPrefix: 'https://g.alicdn.com/kg/workbox/3.3.0/'});
</code>

References

Workbox official documentation

“The Magic of Workbox 3.0”

Photo by Peter Wendt on Unsplash
FrontendCaching StrategiesPWAService WorkerWorkbox
Taobao Frontend Technology
Written by

Taobao Frontend Technology

The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.