Building a PWA in 2019 with Service Workers

 

Well, well, well is your site doing great? If you are reading this article, then I am pretty sure you wish to add few extra features to your site. That’s not bad, in fact one should keep improving their product over time. So here I’ll tell you how you can easily use something called service worker to add some cool features to your website.

 

PWA

Below is a small list of things your site will be able to do:

  • Installable website.
  • Offline capability.
  • Caching.
  • Faster performance.
  • Easy conversion to actual application.

Other benifits included are, increased conversion rate, faster load time on slower network and increased interaction. Over time PWAs have been proven to be benificial for the business aswell as the customer.


Interested to convert your website into a “Progressive Web APP”? I’m too excited to tell you how you could do that. Do share your implementation with me on twitter. I’ll love to see them.


So, there are few steps of building a PWA.

  1. Calling service worker.
  2. Check if active.
  3. If not, register a service worker.
  4. Cache/Route as per rule.
  5. Add PWA data via, manifest.
  6. Done!
Few abbreviations, I’ll use in the post. Do remember them for reference.
PWA for progressive web app, SW for service worker, SW.JS for the sw.js file (service worker JavaScript file.)

STEP 1 (Create/Register Service Worker)


The first step of creating a service worker is to call the service worker file. We will do this by adding a simple JavaScript code into the html file. You can also add this to your JavaScript file if you wish.


<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
    // Use the window load event to keep the page load performance
    window.addEventListener('load', () => {
     navigator.serviceWorker.register('/sw.js');
    });
}
</script>
                

STEP 2 (Importing WORKBOX)


So, let me tell you something about Workbox first. It’s an open source library provided by Google which has predefined rules and routes which will help us to build service worker in a breeze.


Importing Workbox is very simple too. You just need to import the script and check is if loaded or not and display a console log accordingly.


//add this code to your sw.js file (sw.js must be at the root)
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}
                

STEP 3 (Configuring Workbox)


Now everyone wants to configure their service workers differently. I’ll try to cover all the basics so you can customise your service worker mechanism accordingly.


Now let’s begin by making your Google analytics code work offline to.


//Single line to make GA work offline.
workbox.googleAnalytics.initialize();
                

Caching Google Fonts.


// Cache the Google Fonts stylesheets with a stale while revalidate strategy.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.googleapis\.com/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  }),
);

// Cache the Google Fonts webfont files with a cache first strategy for 1 year.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.gstatic\.com/,
  new workbox.strategies.CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxAgeSeconds: 60 * 60 * 24 * 365,
      }),
    ],
  }),
); 

                

Caching your JS and CSS.


workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate(),
); 
                

Caching webpage to reuse them when offline.


//offline 5 html pages
 workbox.routing.registerRoute(
  /\.(?:html)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'webpage',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 5,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  }),
);

                

You can simply use all these modules or use only the one you need to build your service worker.


STEP 4 (Adding Manifest)


Now that we are done with configuring our service worker, lets tell browser about our PWA. We do this via a .json type manifest file.
Now add this to the <head> of your html file.


<!-- PWA Manifest-->
<link rel="manifest" href="/manifest.json" />
                

Then customise the below code and add to your manifest.json file.


{
  "name"              : "APP NAME",
  "short_name"        : "ALT APP NAME",
  "description"       : "APP Short Description",
  "start_url"         : "/index.html",
  "display"           : "standalone",
  "orientation"       : "natural",
  "background_color"  : "Brand Colour Code in hex", 
  "theme_color"       : "Brand Colour Code in hex",
  "icons": [
    {
      "src"           : "https://demo.example.com/images/64.png",
      "sizes"         : "64x64",
      "type"          : "image/png"
    },
    {
      "src"           : "https://demo.example.com/images/128.png",
      "sizes"         : "128x128",
      "type"          : "image/png"
    },
    {
      "src"           : "https://demo.example.com/images/192.png",
      "sizes"         : "192x192",
      "type"          : "image/png"
    },
    {
      "src"           : "https://demo.example.com/images/256.png",
      "sizes"         : "256x256",
      "type"          : "image/png"
    },
    {
      "src"           : "https://demo.example.com/images/512.png",
      "sizes"         : "512x512",
      "type"          : "image/png"
    }
  ]
}
                

STEP 5 (Testing & Debugging)


Now that we have done all the required step lets test our PWA. To test you can simple use inbuilt lighthouse or web.dev to test everything.


Hope it was a helpful article but feel free to give me suggestion or ask for help. Also, if you think this post can be improved, then I’m very open to suggestions. I can be reached easily via email or tweet.