Building Blocks of a Progressive Web App

A quick guide to writing PWA using the building blocks

Gaurav Behere
2 min readFeb 1, 2020

In this article let us focus on building a PWA feature by feature looking at the code we need to write in plain JavaScript.

Note: Please refer to https://developers.google.com/web/progressive-web-apps to get a good understanding of what PWA is.

I have added the code samples below from a PWA starter guide hosted here: https://github.com/gauravbehere/pwa-starter-demo

Service Worker

At the core of a PWA lies a service worker. 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.

Read more about service workers: https://developers.google.com/web/fundamentals/primers/service-workers

Manifest

The web app manifest is a simple JSON file that tells the browser about your web application and how it should behave when ‘installed’ on the user’s mobile device or desktop. Having a manifest is required by Chrome to show the Add to Home Screen prompt.

Read more about manifest: https://developers.google.com/web/fundamentals/web-app-manifest/

Push Notifications

If you ask a room of developers what mobile device features are missing from the web, push notifications are always high on the list. Web push notifications allow users to opt-in to timely updates from sites they love and allow you to effectively re-engage them with customized, relevant content. The Push API and Notification API open a whole new set of possibilities for you to re-engage with your users.

Displaying a notification:

serviceWorkerRegistration.showNotification(title, options);

There are two parts to implementing push notifications:

User Consent

Check if notification is supported. Ask for user consent.

Web Push

  1. Handle push notifications in the service worker. (optional)
self.addEventListener('push', (event) => {
event.waitUntil(self.registration.showNotification("test", {body: event.body}));
});

2. Set up web push with firebase

Read more about how web push works: https://developers.google.com/web/fundamentals/push-notifications/how-push-works

Background Sync

Background sync is a web API that lets you defer actions until the user has stable connectivity. This is useful for ensuring that whatever the user wants to send, is actually sent.

Registering Sync

Performing Sync

Read more about background sync: https://developers.google.com/web/updates/2015/12/background-sync

Get started, write your PWA now!

I have added a PWA starter app here: https://github.com/gauravbehere/pwa-starter-demo. You can refer to the folder structure, HTML elements & other stuff in this repo.

--

--

Gaurav Behere
Gaurav Behere

Written by Gaurav Behere

Full-stack engineer, drummer, running on JS, Python & Music. “Frameworks & Libraries come & go, JS stays ❤” https://www.linkedin.com/in/gauravbehere/

No responses yet