All Articles

PWA Service Worker

A simple guide for getting PWA playing nicely with your web page.

What is a Progressive Web App (PWA)?

A Progressive Web App (PWA) is a web app that uses modern web capabilities to deliver an app-like experience to users.

Why build a Progressive Web App?

Building a high-quality Progressive Web App has incredible benefits, making it easy to delight your users, grow engagement and increase conversions.

  • Worthy of being on the home screen
  • Work reliably, no matter the network conditions
  • Increased engagement
  • Improved conversions

What is required to build a PWA?

To be considered a Progressive Web App, your app must be:

  • Have a responsive website
  • Work for every user, regardless of browser choice
  • Using HTTPS across your website
  • Easily share via URL and not require complex installation

What does a service-worker do?

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.

Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.

Things to note about a service worker:

  • It’s a JavaScript Worker, so it can’t access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed.

  • Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.

  • It’s terminated when not in use, and restarted when it’s next needed.

  • Service workers make extensive use of promises.

An example Service-worker.js

const cacheName = 'SITE NAME';
const filesToCache = [
  '/',
  '/styles.css',
  '/css/bootstrap.min.css',
  '/css/line-icons.css',
  '/css/magnific-popup.css',
  '/dist/css/allergy.css',
  '/js/lazysizes.min.js',
  '/img/Color-logo-no-background.png',
  '/img/google-play-badge.png',
  '/img/app-store-badge.png'
];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

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

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