How to create a Progressive Web Application (PWA)

Fasty allow you now to create PWA easily. I invite you to read the Google documentation about it.

Requirements are : 

  • Your app must use HTTPS protocol
  • You have to define a manifest.json file
  • You must have a service worker for managing you app and it's offline content

manifest.json

Create a new page and call it Manifest and set the slug to manifest.json

{
  "short_name": "Fasty's Blog",
  "name": "Fasty's Blog",
  "icons": [
    {
      "src": "https://resize.ovh/r/62ca5490-c029-11e9-b8b8-7dffa8888a54/192",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "https://resize.ovh/r/62ca5490-c029-11e9-b8b8-7dffa8888a54/512",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/",
  "background_color": "#3367D6",
  "display": "standalone",
  "scope": "/",
  "theme_color": "#3367D6"
}

Install your service worker

On your home page, add this javascript code

<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('{{ dataset | title=service-worker.js | js | only_url#js }}', { scope: '/' })
        .then((reg) => {
        });
    });
  }
</script>

{{ dataset | title=service-worker.js | js | only_url#js }} is a new shortcut for getting an URL from a dataset content. This one mean : Get dataset with title == service-worker.js and prepare the URL for the js field and set the extension to js.

It will return an URL like: /:lang/ds/:key/:field/:rev./:ext (e.g. /en/ds/34941052/js/_aDb5i8y--_.js

Create your service worker

We are going to use a datatype to manage our javascript scipts

Once done, you'll be able to manage your scripts within datasets menu. Create a new one with service-worker.js as title and this code as content :

const CACHE_NAME = "fasty-0-4"; // use anything different
const urlsToCache = [
  '/', '/en', '/en/home' // Define the cache you want
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        return cache.addAll(urlsToCache);
      })
  );
});

// Serve cache
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {  
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

Add Install process bar

Now you just need to add in your layout JS the code for displaying the app installation bar.

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  deferredPrompt = e;
  showInstallPromotion();
});

Check the PWA status

It's time to check if your PWA is ready (or not). For that, simply open the developer console in Google Chrome and go to the Audit tab. Generate the report and check result.

This is what I have for https://pwa.fasty.ovh


Leave a comment