Get set up with a Progressive Web App Service Worker on your site in 5 min

If your site isn’t already set up with a Service Worker, Chrome’s debugging tools throw a few errors under the “Progressive Web App” section of webpage auditing.

Current page does not respond with a 200 when offline

start_url does not respond with a 200 when offlineNo usable web app manifest found on page.

Does not register a service worker that controls page and start_url

Web app manifest does not meet the installability requirements Failures: No manifest was fetched.

A service worker enables your web app to be reliable in unpredictable network conditions. Learn more.

You’ll need 2 basic elements for a service worker, a sw.js file and a small snippet of code to be included on all pages you want the service worker active on.

Step 1: sw.js

This is the sw.js code. You’ll likely want to upload this code to your website example.com/sw.js

const cacheName = `serviceworker-0.6.18`;
self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(cacheName).then(cache => {
      return cache.addAll([
        `/`,
        `/index.html`,
        `/styles/main.css`,
        `/scripts/main.min.js`,
      ])
          .then(() => self.skipWaiting());
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.open(cacheName)
      .then(cache => cache.match(event.request, {ignoreSearch: true}))
      .then(response => {
      return response || fetch(event.request);
    })
  );
});

Before uploading the code, you’ll need to modify the cache.addAll file list to include the required javascript/css files for your site, logos and required images, as well as any pages you would like accessible while your user is offline. Delete index.html and the styles/scripts files included unless your files are located in the same location. I suggest including your top 3 pages (homepage, contact page, etc). Be aware, these pages will be loaded in the background by every browser visiting your site. You may also want to change “serviceworker-0.6.18” to the name of your site/service-worker.

Step 2. <script>

The second required element is the service worker script:

      if('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/sw.js', { scope: '/' })
          .then(function(registration) {
                console.log('Service Worker Registered');
          });

        navigator.serviceWorker.ready.then(function(registration) {
           console.log('Service Worker Ready');
        });
      }

Place this code within a <script> </script> element somewhere on your page.  You can use the console.log messages to ensure your service worker is getting registered properly.

Step 3. manifest.json

Although not required, you can add a manifest.json file to the root of your website to enable it to be installed as an app.

{
  "name": "Website Full Name",
  "short_name": "WebsiteShortName",
  "icons": [
    {
      "src": "/images/icons-192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/images/icons-512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "lang": "en-US",
  "start_url": "/",
  "display": "standalone",
  "background_color": "white",
  "theme_color": "white"
}

You’ll need a png image at least 192×192 to pass all the Chrome audits.

Leave a Comment