magic is happening

How to create a progressive web app (PWA) in laravel 5

The progressive web app is the new trend as well as the need for the present time. I hope before getting in the “HOW” part you know what is exactly a PWA is. If you don’t let’s say, just for the sake of brief introduction they are web apps but also can be installed over the devices like desktop and mobiles.

I am adding a demonstration video of how PWA works here below.

So, by this video i am assuming that you have understand that how a PWA works.

How a make a PWA

lets come to the main question, how to do this.

Before getting into it let me make one thing very clear to you. Making a PWA is not that hard that it seems to be. So, chill it will be fun

To make a PWA you need three things. Listed below

  1. manifest.json
  2. Checking all the Audit test from google lighthouse
  3. Service worker

Once these three things are done you are good. So, without any further ado, let’s get the show running.

manifest.json

Consider this file as the guide to tell the browser that from were, what is to be taken. It’s simple and easy to create. The sample code is below. Also, you can take all the code used in this tutorial from my git repo. link is at the end of the article.

{
     "short_name": "Short name of the application",
     "name": "Name of the application",
     "icons": [
         {
             "src": "/images/path/image.png",
             "type": "image/png",
             "sizes": "192x192"
         },
         {
             "src": "/images/path/image.png",
             "type": "image/png",
             "sizes": "512x512"
         }
     ],
     "start_url": "/",
     "background_color": "#ffffff",
     "display": "standalone",
     "scope": "/",
     "theme_color": "#e5e5e5"
 }

you can find all the details about all the attribute of manifest.json here. Once created, Add this to your ROOT DIRECTORY. In Case of LARAVEL, PUBLIC DIRECTORY.

In the next step, you have to link this file to your HTML. adding in the LAYOUT is the best option for laravel

<link rel="manifest" href="/manifest.json">

<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#e5e5e5">

I have mentioned some other meta also which will ease the creation process. After adding the manifest.json and linking it to the HTML you will be able to see it in the application section of the google development tool.

Checking for Audits

After adding manifesto to the system, we will get all the audits to check. you can find the audit in your google chrome developers console. All you have to do is check the appropriate option and run the test.

In case any test fails, do not worry. Tests in the installable section are the only mandatory for the app to work. If the test fails in that section get the suitable fixes. You can put the issue in the comment section. Maybe I could be of any help to you.

Service Worker

Last and final step of the process in the initiating and using the service worker. The process can roughly divided into 2 part.

  1. Adding the service worker
  2. Using the service worker

Adding the service worker

For adding the service container, add the below code in the file.

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
        navigator.serviceWorker.register('/sw.js').then(function (registration) {
            console.log('ServiceWorker registration :', registration.scope);
        }).catch(function (error) {
            console.log('ServiceWorker registration failed:', errror);
        });
    });
}

This code is registering a sw.js that means we have to create a sw.js which will serve as our service worker.

Special NOTE:

please put service worker and manifest.json on same level. It is highly recommended that you put both of them in the public directory. if they are not on same level scope issue will be there.

Using the service worker

Once added now we have to add the code in sw.js. Please add the following code in the sw.js.

var CACHE_NAME = 'pwgen-cache-v1';

/**
 * The install event is fired when the registration succeeds.
 * After the install step, the browser tries to activate the service worker.
 * Generally, we cache static resources that allow the website to run offline
 */
self.addEventListener('install', async function () {
    const cache = await caches.open(CACHE_NAME);
    cache.addAll([
        'all files to be cached here'
    ])
});

self.addEventListener('fetch', function (event) {});

You can find a complete detailed explanation of the added install and fetch functions here

Now for the final showdown all, we have to call the prompt to add the app. to do that we have to add the following code to the same file we have registered the service worker.

window.addEventListener('beforeinstallprompt', saveBeforeInstallPromptEvent);

function saveBeforeInstallPromptEvent(evt) {
    deferredInstallPrompt = evt;
    deferredInstallPrompt.prompt();
}

The above code will make the prompt for adding the app. And congratulations mate. you got yourself a PWA.

In case of any doubt of query feel free to ask in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close
Social profiles