How to Use Service Workers to Precache Split Code Bundles for Offline Use

In modern web development, providing a seamless offline experience is crucial for user satisfaction. One effective way to achieve this is by using service workers to precache split code bundles. This technique ensures that your web application loads quickly and functions correctly even without an internet connection.

Understanding Service Workers and Code Splitting

Service workers are scripts that run in the background of your browser, intercepting network requests and managing cache. Code splitting involves dividing your JavaScript code into smaller chunks or bundles, which can be loaded on demand. Combining these techniques allows for efficient caching of only the necessary code, reducing load times and improving offline capabilities.

Setting Up Your Service Worker

To start, create a service worker file, typically named sw.js. In this file, you’ll define the caching strategy and specify which files to precache, including your split code bundles.

Registering the Service Worker

Register the service worker in your main JavaScript file:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      })
      .catch(error => {
        console.log('ServiceWorker registration failed:', error);
      });
  });
}

Precache Split Code Bundles

In your sw.js, define the files to cache. This includes your main bundle and the split code chunks:

const CACHE_NAME = 'my-site-cache-v1';
const PRECACHE_URLS = [
  '/',
  '/index.html',
  '/main.js',
  '/chunk-vendors.js',
  '/chunk-commons.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(PRECACHE_URLS))
  );
});

Handling Fetch Events for Offline Access

Intercept fetch requests to serve cached files when offline:

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});

Best Practices

  • Keep your cache updated by deleting old caches during the activate event.
  • Use runtime caching for dynamically loaded split bundles.
  • Test offline functionality thoroughly to ensure all critical assets are cached.

Using service workers to precache split code bundles significantly enhances your web application’s offline capabilities. Proper setup and testing ensure users have a reliable experience regardless of network conditions.