Skip to main content

Quali caratteristiche deve avere un’applicazione web per essere considerata “progregressive”? Sicuramente come molte altre applicazioni sono costruite utilizzando HTML\CSS\JS. Ma cosa di preciso rende un applicazione progressive?

In questo post proverò a creare una PWA, mano a mano aggiungendo dei parametri fin a farla diventare progressive. Al giorno d’oggi il browser chrome permette di installare l’applicativo sullo smartphone, quindi possiamo dire che l’app gira direttamente su chrome.

HTTPS

Prima di tutto come nelle altre applicazioni, bisogna richiedere la connessione sicura, questo servizio è spesso offerto dal tuo provider di hosting.

Inizio sviluppo PWA

Prima di tutto creiamo un piccolo file html su quale si baserà la nostra PWA.

<!DOCTYPE html>
<html lang="it">
<head>
    <title>Webcuser</title>
    <style>
        BODY {
            background-color: #fff;
            color: #342309;
            font-size: 40px;

        }
        DIV {

            display: grid;
            height: 150vh;
        }
    </style>
</head>
<body>
<div>Webcuser</div>
</body>
</html>

Manifest

Il manifest principalmente si utilizza per indicare che questo file fa parte dalla nostra PWA. Si indica attraverso il tag link che si inserisce nel head della pagina.

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

Icona

Dobbiamo aggiungere l’icona all’app che abbiamo generato, le dimensioni di una icona devono essere 144×144 nel formato PNG, SVG o WebP.

Icona Webcuser per PWA

Service Worker

Dopo l’aggiunta del manifest, un altra opzione obbligatoria è l’aggiunta del service worker che si inserisce nel index.html e lo script è il seguente.

<script>
    if ("serviceWorker" in navigator) {
        self.addEventListener("load", async () => {
            const container = navigator.serviceWorker;
            if (container.controller === null) {
                const reg = await container.register("sw.js");
            }
        });
    }
</script>

Il contenuto del file sw.js deve essere:

'use strict';
function hndlEventFetch(evt) {}
self.addEventListener('fetch', hndlEventFetch);

Cache

L’ultimo passaggio è l’aggiunta della funzionalità di utilizzare la cache, questo è il codice che deve contenere il service worker per la vostra pwa:

'use strict';
const CACHE_STATIC = 'static-cache-v1';

function hndlEventInstall(evt) {
    /**
     * @returns {Promise<void>}
     */
    async function cacheStaticFiles() {
        const files = [
            './',
            './demo.pwa.json',
            './icon.png',
            './index.html',
            './sw.js',
        ];
        const cacheStat = await caches.open(CACHE_STATIC);
        await Promise.all(
            files.map(function (url) {
                return cacheStat.add(url).catch(function (reason) {
                    console.log(`'${url}' failed: ${String(reason)}`);
                });
            })
        );
    }

    //  wait until all static files will be cached
    evt.waitUntil(cacheStaticFiles());
}

function hndlEventFetch(evt) {
    async function getFromCache() {
        const cache = await self.caches.open(CACHE_STATIC);
        const cachedResponse = await cache.match(evt.request);
        if (cachedResponse) {
            return cachedResponse;
        }
        // wait until resource will be fetched from server and stored in cache
        const resp = await fetch(evt.request);
        await cache.put(evt.request, resp.clone());
        return resp;
    }

    evt.respondWith(getFromCache());
}

self.addEventListener('install', hndlEventInstall);
self.addEventListener('fetch', hndlEventFetch);

Conclusione

Per creare una web applicazione dovete seguire questi 6 semplici passaggi.

  • Https
  • File index
  • Manifest
  • Icona
  • Service worker
  • Cache

Seguendo questi passaggi riuscirai ad installare la PWA sul tuo smartphone.

Leave a Reply

Cosa rallenta il tuo sito web?