Service Workers | How To PWA

Service Workers | How To PWA

A virtual proxy between the browser and the network is indeed the Service Worker. Finally, they resolve issues with which front-end developers have struggled for years, most importantly how to properly cache a website’s resources and make them usable when the device goes offline.

They run on a separate thread from our page’s main JavaScript code, and have no access to the DOM structure at all.The API is non-blocking, and can send and receive exchange between different contexts, which provides a different approach from conventional web programming. You can give a service worker something to put the spotlight on, and get the result once a promise-based approach is ready.

They can do much more than just" offer offline capabilities, along with handling notifications, dense calculations on a separate thread, etc. Service workers are very efficient because they can take control of network requests, change them, serve custom cache-retrieved responses, or fully synthesize responses.

Manifest.json

That JSON file sets the following variables:

  • Name: name of the application
  • Short name: the app’s short name
  • Icons: declaration of icons behind the application
  • Start url: home page app
  • Display: standalone (standalone application), browser, fullscreen (like a web page)
  • Background Color: background color when the app is launched
  • Theme-color: the theme color used in the app

Example

{
  "name": "Cristian Marin",
  "short_name": "Marin",
  "description": "Backend Developer (Spring Boot & Laravel)",
  "theme_color": "#1da1f2",
  "background_color": "#ffffff",
  "display": "fullscreen",
  "scope": "/",
  "start_url": "/blog/?source=pwa",
  "orientation": "portrait",
  "icons": [
    {
      "src": "/maskable_icon.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "/apple-icon-180x180.png",
      "sizes": "180x180",
      "type": "image/png"
    },
    {
      "src": "/android-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"
    }
  ],
  "shortcuts": [
    {
      "name": "Stories?",
      "short_name": "Chat",
      "description": "Its time to learn something new",
      "url": "/blog?source=pwa",
      "icons": [{
        "src": "/images/pwa/blog.png",
        "sizes": "160x160",
        "type": "image/png"
      }]
    }
  ]
}

Next step is link this file throughtag

<head>

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

<meta name="description" content="Description">
<meta name="apple-mobile-web-app-title" content="Description">
<meta name="theme-color" content="#1da1f2" />

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

</head>

Service Work .js

Its just a JavaScript file that the browser executes in the background, allowing for functions that do not require either the web page or user interaction (such as push notification).

'use strict';

const CACHE_NAME = 'static-cache-v1';
const FILES_TO_CACHE = [
  '/offline.html',
];

self.addEventListener('install', (evt) => {
  console.log('[ServiceWorker] Install');
  evt.waitUntil(
      caches.open(CACHE_NAME).then((cache) => {
        console.log('[ServiceWorker] Pre-caching offline page');
        return cache.addAll(FILES_TO_CACHE);
      })
  );
  self.skipWaiting();
});

self.addEventListener('activate', (evt) => {
  console.log('[ServiceWorker] Activate');
  evt.waitUntil(
      caches.keys().then((keyList) => {
        return Promise.all(keyList.map((key) => {
          if (key !== CACHE_NAME) {
            console.log('[ServiceWorker] Removing old cache', key);
            return caches.delete(key);
          }
        }));
      })
  );
  self.clients.claim();
});

self.addEventListener('fetch', (evt) => {
  console.log('[ServiceWorker] Fetch', evt.request.url);
  if (evt.request.mode !== 'navigate') {
    return;
  }
  evt.respondWith(
      fetch(evt.request)
          .catch(() => {
            return caches.open(CACHE_NAME)
                .then((cache) => {
                  return cache.match('offline.html');
                });
          })
  );
});

Now we can register our Service Worker through a couple of lines

<script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
            .then((reg) => {
              console.log('Service worker registered.', reg);
            });
      });
    }
  </script>

Offline.html

This is the easiest part since the offline.html is just a page that is displayed when there is no connection. If you are good with JavaScript you can do some fun things to keep your users entertained when there is no connection.

Share on:
comments powered by Disqus