Progressive Web Apps: Going Offline

1. Welcome

In this lab, you'll take an existing web application and brand it work offline. This is the start in a series of companion codelabs for the Progressive Spider web App workshop. There are seven more codelabs in this serial.

What you'll learn

  • Write a Service Worker past hand
  • Add a Service Worker to an existing web application
  • Use the Service Worker and the Enshroud Storage API to make resources available offline

What yous should know

  • Basic HTML and JavaScript

What you will need

  • A browser that supports Service Workers

two. Get Set up

Commencement past either cloning or downloading the starter lawmaking needed to complete this codelab:

If yous clone the repo, make sure you're on the starter branch. The zip file contains the code for that branch, too.

This codebase requires Node.js 14 or higher. In one case yous have the code available, run npm ci from the command line in the code'due south binder in gild to install all of the dependencies you'll need. Then, run npm start to start the development server for the codelab.

The source lawmaking's README.md file provides an explanation for all distributed files. In addition, the following are the cardinal existing files yous'll be working with throughout this codelab:

Key Files

  • js/master.js - Chief application JavaScript file
  • service-worker.js - Awarding'southward service worker file

iii. Test Offline

Before making any changes, let'south examination to show that the web app doesn't currently piece of work offline. To do so, either take our computer offline and reload the web app, or, if you lot're using Chrome:

  1. Open up up Chrome Dev Tools
  2. Switch to the Application tab
  3. Switch to the Service Workers section
  4. Cheque the Offline checkbox
  5. Refresh the page without closing Chrome Dev Tools

Chrome Dev Tools Application tab opened to Service Workers with the Offline checkbox checked

With the site tested and successfully declining to load offline, information technology'south time to add some online functionality! Uncheck the offline checkbox and continue to the next stride.

4. Take It Offline

It's time to add a bones service worker! This will happen in two steps: registering the service worker and caching resources.

Register a Service Worker

In that location'due south already an empty service worker file, so to make sure the changes prove up, let'due south register it in our application. To do so, add the following lawmaking to the superlative of js/main.js:

                        import swURL from 'sw:../service-worker.js';  // Register the service worker if ('serviceWorker' in navigator) {   // Wait for the 'load' event to not block other work   window.addEventListener('load', async () => {     // Try to register the service worker.     try {       const reg = expect navigator.serviceWorker.register(swURL);       console.log('Service worker registered! 😎', reg);     } catch (err) {       console.log('😥 Service worker registration failed: ', err);     }   }); }                                              

Caption

This code registers the empty service-worker.js service worker file in one case the folio has loaded, and just if the site supports service workers.

Precache resources

In society to go the web app working offline, the browser needs to be able to respond to network requests and choose where to road them. To exercise then, add the following to service-worker.js

                        // Cull a cache name const cacheName = 'cache-v1'; // Listing the files to precache const precacheResources = ['/', '/index.html', '/css/manner.css', '/js/main.js', '/js/app/editor.js', '/js/lib/deportment.js'];  // When the service worker is installing, open up the cache and add together the precache resources to it cocky.addEventListener('install', (event) => {   console.log('Service worker install event!');   event.waitUntil(caches.open(cacheName).and so((cache) => cache.addAll(precacheResources))); });  cocky.addEventListener('activate', (event) => {   console.log('Service worker activate event!'); });  // When there's an incoming fetch asking, endeavour and respond with a precached resource, otherwise fall back to the network self.addEventListener('fetch', (outcome) => {   console.log('Fetch intercepted for:', issue.request.url);   result.respondWith(     caches.lucifer(event.asking).then((cachedResponse) => {       if (cachedResponse) {         return cachedResponse;       }       render fetch(consequence.request);     }),   ); });                                              

At present, return to the browser, close your preview tab, and open it back up once more. You lot should come across panel.logs corresponding to the different events in the service worker!

Next, go offline again and refresh the site. Yous should see that it loads even though you're offline!

Explanation

During the service worker's install event, a named cache is opened using the Cache Storage API. The files and routes specified in precacheResources are and so loaded into the cache using the enshroud.addAll method. This is called precaching because it preemptively caches the set of files during install fourth dimension as opposed to caching them when they're needed or requested.

One time the service worker is controlling the site, requested resources laissez passer through the service worker like a proxy. Each asking triggers a fetch event that, in this service worker, searches the cache for a lucifer, if there's a match, responds with cached resource. If there isn't a match, the resources is requested ordinarily.

Caching resource allows the app to work offline by avoiding network requests. At present the app can respond with a 200 status lawmaking when offline!

5. Congratulations!

You've learned how to accept your web app offline using service workers and the cache storage API.

The adjacent codelab in the serial is Working with Workbox