DEV Community

Cover image for Simple way to convert existing HTML web application to a PWA
Rohith Gilla
Rohith Gilla

Posted on • Updated on • Originally published at dev.to

Simple way to convert existing HTML web application to a PWA

Hey everyone, this is my first post so wish me luck!

TLDR;

You will have the template and files for converting your HTML page to a PWA like godspeed.

So we need the following files

  1. manifest.json
  2. sw.js (service worker)

An example of manifest.json can be found in the following gist.

This is how a manifest.json file looks like.

{
  "name": "CoolApp",
  "short_name": "Cool",
  "theme_color": "#2196f3",
  "background_color": "#2196f3",
  "display": "standalone",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/img/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "splash_pages": null
}
Enter fullscreen mode Exit fullscreen mode

Now, one of the most crucial options in manifest.json is display.
standalone gives us a proper UI when installed as a native application.
You can explore other options here.

Now coming to generating icons. I strongly suggest this website, which works like a charm, it generates both manifest.json and icons.

Note: When uploading the image for generating icons, please make sure the size of the image you are uploading is 512 X 512.

Now coming to our sw.js file.

/*
 global workbox
*/

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

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
  workbox.routing.registerRoute(
    new RegExp(".*.js"),
    new workbox.strategies.NetworkFirst()
  );
  workbox.routing.registerRoute(
    /\.css$/,
    new workbox.strategies.StaleWhileRevalidate({ cacheName: "css-cache" })
  );

  workbox.routing.registerRoute(
    /\.(?:png|jpg|jpeg|svg|gif)$/,
    new workbox.strategies.CacheFirst({
      cacheName: "image-cache",
      plugins: [
        new workbox.expiration.Plugin({
          // Cache only 20 images.
          maxEntries: 20,
          // Cache for a maximum of a week.
          maxAgeSeconds: 7 * 24 * 60 * 60
        })
      ]
    })
  );
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}
Enter fullscreen mode Exit fullscreen mode

It uses Google Workbox for PWA support. It handles almost everything, we can sit back and relax.

Now there are a couple more steps until your website is a PWA.

We edit the index.html file.

  • Add the following line in the <head> tag.
<link rel="manifest" href="/manifest.json">
Enter fullscreen mode Exit fullscreen mode

Which ensures manifest.json is linked.

  • Now add the following script, to finish the process.
<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

        // Check compatibility for the browser we're running this in
        if ("serviceWorker" in navigator) {
            if (navigator.serviceWorker.controller) {
                console.log("[PWA Builder] active service worker found, no need to register");
            } else {
                // Register the service worker
                navigator.serviceWorker
                    .register("sw.js", {
                        scope: "./"
                    })
                    .then(function (reg) {
                        console.log("[PWA Builder] Service worker has been registered for scope: " + reg.scope);
                    });
            }
        }
    </script>

Enter fullscreen mode Exit fullscreen mode

Annnnnd Done. TADA!! when you open the application on an android phone or chrome browser in any desktop you should see an install button.

Bonus

To add notification support to Progressive Web Applications a.k.a PWA.
Just add the following snippet after registering the Service Worker.

// To ask permission for notification.
Notification.requestPermission(function(status) {
  console.log("Notification permission status:", status);
});

// To send a notification
function displayNotification() {
  if (Notification.permission == "granted") {
    navigator.serviceWorker.getRegistration().then(function(reg) {
      reg.showNotification("Thanks for subscribing for to our notifications.");
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

You can call the displayNotification function, it sends the notification to the users.

P.S: In this article, I didn't explain what each line of the code does, it's a TL;DR article to make an existing web site a Progressive Web Application.

Thanks, hope you liked it.

Top comments (0)