Day 2: Adding Service Workers for Offline Support


Today, you’ll add a service worker to your React app to enable offline support. Service workers cache resources so your app can function without a network connection, allowing users to interact with your app even when offline.

What You Will Do Today:

  1. Understand the role of service workers in PWAs.
  2. Register the default service worker.
  3. Customize caching strategies to cache specific assets and routes.

Step 1: Understanding Service Workers

A service worker is a JavaScript file that runs in the background, separate from the main application. It acts as a network proxy, allowing it to cache assets and intercept network requests to serve cached data when the network is unavailable.

  • Caching: Service workers store static resources, so the app works offline or on low connectivity.
  • Lifecycle: Service workers have a lifecycle independent of the app, making them ideal for caching.

Step 2: Registering the Default Service Worker

create-react-app includes a basic service worker setup in public/service-worker.js and src/serviceWorkerRegistration.js. To register it:

  1. In src/index.js, import serviceWorkerRegistration and call the register() function:
   import React from 'react';
   import ReactDOM from 'react-dom';
   import App from './App';
   import './styles.css';
   import * as serviceWorkerRegistration from './serviceWorkerRegistration';

   ReactDOM.render(
     <React.StrictMode>
       <App />
     </React.StrictMode>,
     document.getElementById('root')
   );

   // Register the service worker
   serviceWorkerRegistration.register();
  1. By registering the service worker, you enable basic offline support. When users load the app, files are cached, allowing them to access previously loaded content even if they lose connectivity.
See also  Groovy Scripting for Jenkins Pipelines

Step 3: Customizing the Service Worker for Caching Strategies

Let’s customize the service worker to cache additional assets and create caching strategies that determine how resources are stored and retrieved.

  1. Open public/service-worker.js. You’ll add logic here to manage caching.
  2. To cache assets on the first load, update service-worker.js as follows:
   const CACHE_NAME = 'my-pwa-cache-v1';
   const urlsToCache = [
     '/',
     '/index.html',
     '/static/js/bundle.js',
     '/static/css/main.css'
   ];

   self.addEventListener('install', (event) => {
     event.waitUntil(
       caches.open(CACHE_NAME).then((cache) => {
         console.log('Opened cache');
         return cache.addAll(urlsToCache);
       })
     );
   });

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

   self.addEventListener('activate', (event) => {
     const cacheWhitelist = [CACHE_NAME];
     event.waitUntil(
       caches.keys().then((cacheNames) => {
         return Promise.all(
           cacheNames.map((cacheName) => {
             if (!cacheWhitelist.includes(cacheName)) {
               return caches.delete(cacheName);
             }
           })
         );
       })
     );
   });

Explanation of Code:

  • CACHE_NAME: The name of the cache storage for easy versioning.
  • urlsToCache: A list of URLs and assets to cache during the install phase.
  • install event: Caches the urlsToCache list during the service worker installation.
  • fetch event: Checks the cache for each request. If available, it serves the cached resource; otherwise, it fetches from the network.
  • activate event: Cleans up old caches when a new service worker version is activated.

Step 4: Testing Offline Functionality

  1. Open your app in Google Chrome and open Developer Tools (F12 or right-click and select “Inspect”).
  2. Go to the Application tab and select Service Workers on the left sidebar.
  3. Check Offline under the Network section to simulate offline mode.
  4. Refresh the page. You should see the app load from the cache, demonstrating that it works offline.

Summary

Today, you added a service worker to your React app to enable offline support by caching key assets. You configured caching strategies to serve cached data when the app is offline.

See also  Guide to download files from WSL (Windows Subsystem for Linux) to your Windows machine using Visual Studio Code

Tomorrow, you’ll create a manifest file and configure app icons to make your PWA installable.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.