App DevelopmentWeb Development

A How-To Guide to Progressive Web Apps

The adoption of Progressive Web Apps (PWAs) is growing faster than ever. Now that Apple has allowed the necessary features on iOS and macOS devices, the last major platform to deliver progressive web app capabilities, sites using service workers can finally deliver fast and offline experiences to all of their end users. There is no surprise why more site owners are shifting towards a progressive web app model.

What are the Benefits of Progressive Web Apps?

  • Simply put, PWAs are cheaper than a full suite of mobile apps plus a website. Everything is under a single maintainable codebase.
  • Unlike traditional web, we have access to amazing features for user retention that native apps have been using for years, such as: offline usage, push notifications, and background syncing.
  • Deploying a progressive web app is as fast as you can deploy updates to your website. There is no need to purchase a license to host the application in an app store.
  • Progressive web apps offer significantly faster load speeds than native apps and traditional websites.
  • Users just aren’t downloading native apps anymore.
  • But most importantly, you can transform your existing website into a PWA with only a few tweaks!

Getting your website on a Home Screen

Every website can benefit from the most basic progressive web app functionality. Just having a home screen icon can drastically increase user retention and engagement.

To get this far we only need a couple of changes.

Configuring the Manifest

A website’s manifest is a JSON file that tells the browser about the PWA. It includes information like how it should behave, what it’s called, and what images or icons are used to present it.

{
  "short_name": "PWA",
  "name": "Progressive Web App",
  "description": "PWA for testing purposes.",
  "icons": [
    {
      "src": "/images/icons-192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/images/icons-512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/",
  "background_color": "#18D9C4",
  "display": "standalone",
  "scope": "/",
  "theme_color": "#18D9C4"
}

Example manifest configuration


Using this configuration file, we can craft our progressive web app to create the perfect app-like experience for our users: we can decide what icon and title is used when it is on the home-screen, we can set the background color and icon for a splash screen when the application is launched, we can apply a color to the site navigation bar to fit branding colors.

<link rel="manifest" href="/manifest.webmanifest">

HTML manifest code


To deploy, we need to target the manifest via an HTML Link in the page Head. This bit of code will let the client know where the page manifest is so that it can be downloaded and processed.

pwa blog 1 Custom Splash Screen from the manifest

pWA blog 2 Custom Icon and app name


Setting Up a Service Worker

A service worker is a script that runs separately from the web page in the background. It is the backbone of a progressive web app and can be used to cache assets and files so our application can work offline. We can also send and receive messages for background syncing or push notifications. This is a huge win for web since native apps have been using push notifications for years with incredible success at increasing user engagement.

pwa blog 3 Service worker diagram Source


For now, we are just going to set up some very basic image caching since the focus of this article is to get a functioning Install To Home feature.

We will be using Workbox to help us. Workbox is a library created by Google for easily implementing caching. With it, we can take full advantage of the features PWAs offer us.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');

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


workbox.routing.registerRoute(
  new RegExp('/images/.+'),
  new workbox.strategies.CacheFirst()
);

Example service worker - /service-worker.js


The code above will initialize Workbox for us (or alert us in the console if it fails) and then cache assets it receives coming from the images directory.

To deploy this code, we have to register the service worker in the HTML:

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

Example HTML service worker register code

The code above will first check that service workers are supported, then wait for the page to load before attempting to register the service worker.


Creating a Custom Install Experience

With the introduction of the manifest and service worker, we already have a functioning Progressive Web Application. The last thing we need to do is to create a trigger that will prompt users to install the application.

Users can manually install the progressive web app themselves if they know how. But not all of your users understand what a PWA is or how to install one. So creating a noticeable and easy user experience is really important.

<script>
window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  window.deferredPrompt = e;
});
</script>
<button onclick={()=>{
    const deferredPrompt = window.deferredPrompt
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
          console.log('User accepted the A2HS prompt');
        } else {
          console.log('User dismissed the A2HS prompt');
        }
        window.deferredPrompt = null;
    });
}}>Add To Home Screen</button>

Example HTML button and installation code


The above code will store the install prompt then trigger the prompt when the user clicks the Add To Home Screen button. PWA blog 4 Example PWA landing page with a button


PWA blo 5 Example PWA installation process


This is a fairly simple approach, but the action of triggering the prompt can be done in any number of ways: it can be prompted after the user creates an account, or it can be a button tied to the sub-navigation. You can find more examples here. Any way that appears consistent with the design of the rest of the app so that the user does not feel overly cautious and deterred.

PWA 6 Sidebar example source


pwa 7 Landing page example source


And tada! 🎉 Your Progressive Web App is finished. Users should now be able to access and download your web application to the home screen for viewing every time they open their device.

Measuring Performance

Before we finish, it’s important to have some automated testing in place so that the manual process of verifying the progressive web app does not have to be repeated in the future. Lucky for us, we have access to Google Lighthouse which comes with its own PWA tester. You can read more about the programmatic method of running Lighthouse here. But for the sake of brevity we will just look at the testing suite that comes packaged with Chrome!

To perform the PWA Lighthouse test, simply open up the Developer Tools on your Chrome window and visit the Audits tab.

From here we can select the Progressive Web App option and click Generate Report. PWA 8 Audit menu with options to choose from


pwa 9 Audit menu after generating a report


Google Lighthouse can offer a wealth of information about your web application and offer tips on how to resolve these issues. The performance tests are especially powerful, allowing you to measure the speed and size of multiple pages in your web application. This way, you can assume the usability of your website in even the worst cases of network connections. With a programmatic approach, you can run it in your automated testing solutions to ensure you are always providing a great experience to users around the world.

Next Steps

Now that you have a very simple preogressive web app set up, you can now add all sorts of features to it and take your web application even further.

Offline usage and push notifications are especially powerful features to have. Before PWAs, web applications were missing crucial ways to increase user retention. The user had to be actively connected to the webpage in order to continue working offline and receive those notifications. With PWAs, web applications are just as powerful while being much smaller and easier to install!

Progressive Web Apps are the future of web development and together we can bring this new experience to all of our users.

Want to learn more about the value of Progressive Web Apps and how to prepare for the future of web development? Visit our services page.

Want to learn more about building Progressive Web Apps?

Visit Our Services Page

The Downside of Density: Bursting the Tech (Location) Bubble

Re-Opening Means Opening the Tech Bubble As the U.S. starts to re-open, people...

Read the article