Simple Steps to convert WEB to PWA

Simple Steps to convert WEB to PWA

ยท

1 min read

  1. In public/index.html add following:
    <script>
      if ("serviceWorker" in Navigator) {
        window.addEventListener("load", () => {
          navigator.serviceWorker
            .register("/service-worker.js")
            .then((reg) => {
              console.log("worker registered");
            })
            .catch((err) => {
              console.log("Service worker error", err);
            });
        });
      }
    </script>
  1. Create new file in public folder called serviceWorker.js
const CACHE_NAME = "version-1";
const urlToCache = ["index.html", "offline.html"];

this.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      console.log("Opened Cache");
      return cache.addAll(urlToCache);
    })
  );
});

this.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((res) => {
      return fetch(event.request).catch(() => caches.match("offline.html"));
    })
  );
});

this.addEventListener("activate", (event) => {
  const cacheWhiteList = [];
  cacheWhiteList.push(CACHE_NAME);
  event.waitUntil(
    caches.keys().then((cacheNames) =>
      Promise.all(
        cacheNames.map((cacheName) => {
          if (!cacheWhiteList.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        })
      )
    )
  );
});
  1. Download Lighthouse extension

  2. Check if lighthouse report is affirmative to create a PWA

  3. Update your manifest.json file as per requirement

Reference

ย