Turn Your Website Into A Progressive Web APP(PWA)

Category:
PHP
Tags:
PHP
javascript

Krunal Patel
6 months ago

Introduction

In today's fast-paced development environment, users expect websites to load quickly and provide a seamless experience. Progressive Web Apps (PWAs) represent an innovative fusion of web and mobile applications, offering the best of both worlds. By leveraging PWA technology, you can deliver fast, reliable, and engaging experiences to your customers across various devices and platforms.

Creating a Web App Manifest File:

The web app manifest is a JSON file that describes your Progressive Web App (PWA). It includes essential details such as the app name, icons, theme colors, and other configuration options. To integrate the manifest file into your PWA, you'll need to add it within the `<head>` tag of your HTML document, as shown in the snippet below.


<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<!--  manifest  -->
<link rel="manifest" href="./manifest.webmanifest">

</head>


You can add the manifest manually, or you can generate the manifest file using websites such as https://www.simicart.com/manifest-generator.html.


Below is the screenshot of the generated manifest JSON file with icons.



After clicking on the 'Generate Manifest' button, a zip file will be downloaded. This zip file contains the icons and the manifest JSON file. You need to add these files to the root directory of your project. Below is a snippet of the downloaded manifest file.


{
    "theme_color": "#f69435",
    "background_color": "#f69435",
    "display": "standalone",
    "scope": "/",
    "start_url": "/",
    "name": "PWA Installation",
    "short_name": "PWA",
    "icons": [
        {
            "src": "./icon-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "./icon-256x256.png",
            "sizes": "256x256",
            "type": "image/png"
        },
        {
            "src": "./icon-384x384.png",
            "sizes": "384x384",
            "type": "image/png"
        },
        {
            "src": "./icon-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ]
}

Add a Service Worker:

A service worker is a JavaScript file that runs in the background and intercepts network requests, serving as a core element of modern PWA technology. It is responsible for various tasks such as push notifications, content updates, data manipulation, and more. The service worker monitors these events and responds accordingly, providing offline capabilities and enhancing the overall user experience of a Progressive Web App.

Please refer to the code below to add sw.js and the script tag just before the closing <body>  tag in your HTML document.

<script src="./sw.js"></script>
    <script>
	if (!navigator.serviceWorker.controller) {
	    navigator.serviceWorker.register("./sw.js").then(function (reg) {
	    	console.log("Service worker has been registered for scope: " + reg.scope);
	    });
	}
</script>

Below is the snippet is the service worker js(sw.js) file:

var staticCacheName = "pwa";
 
self.addEventListener("install", function (e) {
  e.waitUntil(
    caches.open(staticCacheName).then(function (cache) {
        alert('install//');
      return cache.addAll(["/"]);
    })
  );
});
 
self.addEventListener("fetch", function (event) {
  console.log(event.request.url);
 
  event.respondWith(
    caches.match(event.request).then(function (response) {
      return response || fetch(event.request);				
    })
  );
});

Before proceeding, it's essential to check whether the current browser supports the functionality, as service workers are not yet supported by all browsers.


Once confirmed, you should observe an 'Install App' icon appearing on the top right-hand side of the browser's address bar. 

After successful installation, you should see a desktop icon added for easy access to the installed app.


We've successfully implemented a Progressive Web App (PWA)! Thank you for reading.


Good Luck.



DevZone
Made by developer, Made for developers