October 06, 2018

Quickly creating a progressive web app PWA

Progressive web apps are web apps that can avail some native app like features. They can have their own window. They can show notifications and can optionally work offline. To write a minimal PWA, you need a page to display (index.html) and two files for service worker (sw.js) and manifest (manifest.json).

 Note that service worker requires a secure connection so the site has to be served over HTTPS protocol.

First, in the web page add a link tag for manifest.json and in body add a script tag for registering service worker as shown below.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>PWA</title>
        <link rel="manifest" href="manifest.json">
    </head>
    <body>
        <h1>My PWA</h1>
        <script>
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/sw.js');
            }
        </script>
    </body>
</html>

Now we need to create a manifest file. This is a json file that stores properties like app name, starting point, display type, icon etc. Many of these are required to identify your site as PWA.

manifest.json

{
  "name": "My Progressive Web App",
  "short_name": "My PWA",
  "lang": "en-US",
  "start_url": "/index.html",
  "display": "standalone",
  "icons": [
    {
      "src": "http://pngimg.com/uploads/smartphone/smartphone_PNG8511.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

Finally, we need to add a service worker. A service worker is responsible for managing app caches in the site. In our case, we cache list of static files in install event and then in fetch event we check cache before fetching file.

sw.js

/* Cache static files for offline availability */  
self.addEventListener('install', event => {
  event.waitUntil(caches.open('static')
    .then(cache => cache.addAll(['/', 'manifest.json', 'sw.js']))  
  )
});

/* Fetch file if not in cache */
self.addEventListener('fetch', event => {
  event.respondWith(caches.match(event.request) 
    .then(cached => cached || fetch(event.request))
  );
}); 

Serve above three files from a web server (can use localhost without HTTPS) and point your browser to the site. If your browser supports PWA then it may allow you to install a shortcut on the launcher. Note that browsers have criteria for allowing this. The shortcut will open a standalone window. Once loaded, it should display the page offline also.

No comments:

Post a Comment