Quick Intro to PWA-III
Tags: webdev, pwa, tutorial
Published: 2020-04-17 16:24:03

A quick recap, from our previous [tutorial](https://dev.to/maverick_10/quick-intro-to-pwa-ii-19je). We have created folders for *images* & *js* and placed `app.js` in it. We have used `app.js` to fetch the images on the front-end. By now your file structure should replicate something similar to this:

![File_Structure](https://dev-to-uploads.s3.amazonaws.com/i/ushqetpyb399zja2ozw9.PNG)

In this tutorial, we will be looking to add `manifest.json` and `serviceWorker.js`. Before we dive into code, first we need to understand what exactly are these files and why do we need them.

## 1. Manifest.json
By now you are aware that PWA apps are web-apps that work similar to native apps. So there must be something that passes this information to the browser to make our experience similar to it. This is where manifest.json comes into the picture, that is used by the browser as meta-data.

## 2. ServiceWorker
It is a script that runs independently of any other interface scripts in the background. It can be useful for providing various events such as install, download, message, active, fetch, etc.


#### Now let's dive into the code:

* *manifest.json*:
Create a `manifest.json` in the source directory and use these keys-value pair.

`manifest.json`

``` JSON
{
  "name": "SwaraSmruti",
  "short_name": "Swarasmruti",
  "display": "browser",
  "start_url": "index.html",
}
```
We have sent name, display and start_url as the meta-data. The name of the application has been set to _**Swarsmruti**_. The application opens **_index.html_** in the browser.

* *serviceWorker.js*:
Create a `serviceWorker.js` in the source directory.

`serviceWorker.js` 

``` javascript
const staticInstrument = "Swarasmruti-v1";
const assets = [
  "./",
  "./index.html",
  "./stylesheet/app.css",
  "./js/app.js",
  "./images/venna.jpeg",
  "./images/violin.jpg",
  "./images/tabla.jpg",
  "./images/mandolin.jpg",
  "./images/piano.jpg",
  "./images/Electric-Guitar.png",
  "./images/backGroundImage.jpg"
];

self.addEventListener("install", installEvent => {
  installEvent.waitUntil(
    caches.open(staticInstrument).then(cache => {
      cache.addAll(assets);
    })
  );
});

self.addEventListener("fetch", fetchEvent => {
  fetchEvent.respondWith(
    caches.match(fetchEvent.request).then(res => {
      return res || fetch(fetchEvent.request);
    })
  );
});
```
Here we have used 2 events namely **install & fetch**. The install event listener will get the list of resources from `assets` and store it in the cache. The fetch event will be used to check the cache and fetch the `assets`. If it doesn't have the `assets` then, it will try to fetch from the network. If there are issues with network connection then it would provide us a failure result on the console.

Finally, we would be registering the `serviceWorker` in app.js

`app.js`
``` javascript
if ("serviceWorker" in navigator) {
  window.addEventListener("load", function() {
    navigator.serviceWorker
      .register("./serviceWorker.js")
      .then(res => console.log("service worker registered"))
      .catch(err => console.log("service worker not registered", err));
  });
}
```
The `if` block checks **_if_** the serviceWorker is supported before registration. During loading of the webpage, we call the function to register `serviceWorker`. This returns an object of type **Promise**, which would log **_service worker registered_** if successful or log **_service worker not registered_** on the failure of the same.

At last, we are done with our PWA.

![Yeah](https://i.giphy.com/media/S24vAZeES2INy/giphy.gif)

Now we need to check the cache in the browser to get all the `assets` that we mentioned in `serviceWorker.js`. Choose the option of going offline(check the Network tab)in the browser and you will find that it still works with all the assets.

![Assets_in_Cache](https://dev-to-uploads.s3.amazonaws.com/i/wx19cxmv4si3rvdrm02x.PNG)

![Service-Worker_Registration](https://dev-to-uploads.s3.amazonaws.com/i/kwy0rel4efl6l63w27ue.PNG)

## Conclusion:
Now I would like to congratulate all of you on creating your first PWA app. I've provided the link to the repository & there might be variations with the code in the tutorial as I've changed the code to enhance the front end. I've provided various resources that would act as a reference and help in taking giant leaps in the amazing world of PWA's.

Thanks for reading!!!!

## Useful Resources:
1. [Code](https://github.com/suhpin95/Basic-PWA.git)
2. Manifest.json:
   * [Manifest.json](https://web.dev/add-manifest/)
   * [Manifest.json](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json)
   *  [Manifest.json generator](https://app-manifest.firebaseapp.com/)
3. Service Worker:
   * [Service Worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
   * [Service Worker](https://developers.google.com/web/fundamentals/primers/service-workers)