How to make a Progressive Web App ?

Progressive Web Apps have become very much popular nowadays as it allows a website to have many nice features like that of a native app. Some of the features are:

  • Installable: The web app can be added to your device's home screen making it very easy to access
  • App-like Feel: Once installed, the App looks and feels like a native app
  • Offline Access: With the help of service workers the pages can be cached and can be also accessed when offline

Let's get started on making your website a Progressive Web App in 3 Simple Steps

1. Create a Website

If you already have a website skip this step.

We will create a very simple website with a heading of Hello World.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>PWA App</title>
  </head>

  <body>
    <h1>PWA App</h1>
  </body>
</html>

Save this file as index.html

2. Register a service worker

Now in your index.html file we need to add a small script to register a service worker.

<script>
//This is the "Offline page" service worker
//Add this below content to your HTML page, or add the js file to your page at the very top to register service worker
if (navigator.serviceWorker.controller)
{
  console.log('[PWA Builder] active service worker found, no need to register')
}
else
{
  //Register the ServiceWorker
  navigator.serviceWorker.register('pwabuider-sw.js', {
    scope: './'
  }).then(function(reg) {
    console.log('Service worker has been registered for scope:'+ reg.scope);
  });
}
</script>

The above code is from PWA Builder. It is used for registering a service worker if not registered.

In the same folder as the index.html, create a file named pwabuilder-sw.js. This is your service worker that will run in the background and allows you to cache any files for displaying it when user is offline.

Add the following content in the pwabuilder-sw.js file:


self.addEventListener('install', function(event) {
  var offlinePage = new Request('offline.html');
  event.waitUntil(
  fetch(offlinePage).then(function(response) {
    return caches.open('pwabuilder-offline').then(function(cache) {
      console.log('[PWA Builder] Cached offline page during Install'+ response.url);
      return cache.put(offlinePage, response);
    });
  }));
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).catch(function(error) {
        console.error( '[PWA Builder] Network request Failed. Serving offline page ' + error );
        return caches.open('pwabuilder-offline').then(function(cache) {
          return cache.match('offline.html');
      });
    }));
});

self.addEventListener('refreshOffline', function(response) {
  return caches.open('pwabuilder-offline').then(function(cache) {
    console.log('[PWA Builder] Offline page updated from refreshOffline event: '+ response.url);
    return cache.put(offlinePage, response);
  });
});

The above code is from PWA Builder. You can view their website as there are multiple options for caching pages.

Also create an offline.html page that will be cached and served when user is offline.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Offline Page</title>
  </head>

  <body>
    <h1>You are offline</h1>
  </body>
</html>

3. Create manifest.json

Create manifest.json with the following content:

{
      "dir": "ltr",
      "lang": "en",
      "name": "PWA App",
      "short_name": "PWA App",
      "description": "A Demo Application for PWA.",
      "scope": "/",
      "start_url": "/pwa_app/index.html",
      "display": "standalone",
      "theme_color": "#fff",
      "orientation": "any",
      "background_color": "#fff",
      "related_applications": [],
      "prefer_related_applications": false,
      "icons": [
        {
          "src": "logo.png",
          "type": "image/png",
          "sizes": "48x48 96x96 144x144 192x192 512x512"
        }
      ]
  }

Then link this manifest.json file that we just created in your index.html file with the link tag as follows:

<link rel="manifest" href="manifest.json">

Also add a theme-color as follows in index.html file.

<meta name="theme-color" content="#fff"/>

Also add a logo.png file in your project folder so that the manifest.json can actually access it.

That's It! We have made our very first PWA!


Let's Test our PWA

As PWA requires a https for it to work, we will use Github Pages as it serves https pages.

  1. Login to Github
  2. Create a Repository eg. pwa_app
  3. In your local repository execute the following commands:
git init
git add .
git commit -m "pwa app created"
git remote add origin [url to your repo]
git push
  1. Now on your repository page, click on Settings and and enable Github Pages. This will provide you a URL for your website.

  2. Now open your website on your mobile device and you will get a popup to add your website to the Home Screen.

To check how well your PWA App follows the PWA rules you can use Lighthouse. Lighthouse can be used from chrome's Audit window by selecting Progressive Web App and clicking Run Audit.

🚀That's it! You have created your very first Progressive Web App!🚀


Tags: