loading...

Intro to (Progressive) Web Apps

sudhakar3697 profile image Sudhakar RS Updated on ใƒป6 min read

How to start Web Development?

Say hello and get to know the concepts of the Internet, IP, WWW, Browser, Client-Server Architecture, HTTP(S), DNS, Search Engine, URL, API.

Web page

A document which can be displayed in a web browser, written in the HTML language, identified uniquely on web using URL.

Website/Web App

A Website or A Web app is a collection of web pages.

Web server

A computer that hosts a website on the Internet.

Technologies used and their standards

HyperText Markup Language (HTML)

The most basic building block of the Web. It defines the meaning and structure of web content.

Cascading Style Sheets (CSS)

A stylesheet language, describes a web page's appearance/presentation.

JavaScript

A lightweight, interpreted, object-oriented language with first-class functions, used in Web pages for describing functionality/behavior.

WebAssembly

TL;DR Running C/C++/Rust code on Web

WebAssembly is a new type of code that can be run in modern web browsersโ€Šโ€”โ€Šit is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++ with a compilation target so that they can run on the web.

Web API/ Browser API

Not part of JavaScript, Provided by the host environment (Browser). The most important one is the Document Object Model (DOM), used to manipulate the document. There are Fetch (Communicating with server), Client-side storage, Device, Audio/Video, Graphics APIs, Web Workers API (To run a script in a background thread separate from the main execution thread), WebSockets, Server-sent events, Permissions API, etc.

There are Third-party APIs also (Ex. Twitter API, Google Maps API, etc).

Engines used in Major browsers

Browser Rendering Engine (Transforms HTML & other resources of a web page into an interactive visual representation on a user's device) JavaScript Engine (executes JavaScript code)
Chromium, Google Chrome, Microsoft Edge, Opera, Brave Blink V8
Firefox Gecko SpiderMonkey
Internet Explorer Trident Chakra
Microsoft Edge (Initial) EdgeHTML Chakra
Safari WebKit JavaScriptCore (SquirrelFish)

What are Progressive Web Apps (PWA)?

Web apps that are enhanced with native app-like features such as installation, offline support & push notifications. Website++ ๐Ÿ˜œ.

  • Discoverable - From web search results/ app stores (Google Play Store (using TWA), Microsoft Store, etc.)
  • Installable - Like an app, Install prompt can be customized
  • Re-engageable - Sends push notifications like native apps
  • Network Independent - Works offline or in low-network conditions
  • Progressive (Cross-browser compatibility) - Experience scales up (or down) with device capabilities using Latest Web APIs
  • Safe - Only works with HTTPS (You may use letsencrypt.org)
  • Responsive Design - Adapting to the screen size, orientation & input method
  • Linkable - Share and launch from a standard hyperlink
  • Best practices - Improve the Efficiency, follow Semantics, Accessibility (A11y), Internationalization (i18n), Localization (i10n), usage of emerging Web APIs

Why PWAs?

  • Improved User Experience
  • Easy to develop & maintain
  • Cross-platform & native feel

Let's try one

The following are the two major components of a PWA.

  • Service Workers, a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.
  • Web app manifest (A JSON file describing key info about your web app (such as icons, language, and URL entry point))

Add a 'manifest.json' file which has a name, icon, color, display (used to customize the browser UI for the app) attributes.

manifest.json
{
  "short_name": "test",
  "name": "pwa test",
  "icons": [
    {
      "src": "/icon.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/icon.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/",
  "background_color": "#3367D6",
  "display": "standalone",
  "theme_color": "#3367D6"
}

'index.html' imports the 'manifest.json' file. Safari has only partial support for manifest config. It takes attributes using meta tags.

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>pwa test</title>
  <link rel="manifest" href="/manifest.json">
  <!-- Add to home screen for Safari on iOS -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="pwa test">
  <link rel="apple-touch-icon" href="icon.png">
  <meta name="msapplication-TileImage" content="icon.png">
  <meta name="msapplication-TileColor" content="#3367D6">
</head>
<body>
  <h1>Hi Everyone!</h1>
  <script>
    window.addEventListener('load', async () => {
      if ('serviceWorker' in navigator) {
        try {
          const registration = await navigator.serviceWorker.register('/sw.js');
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
                  } catch (err) {
          console.error(err);
        }
      }
    });
  </script>
</body>
</html>

A service worker is registered using 'serviceWorker.register()'. It has 'install', 'activate', 'fetch' events. Let's add 'sw.js'. The 'sw.js' has event handlers which handles the caching of our app.

sw.js
const dataCacheName = 'pwa-test-data';
const cacheName = 'pwa-test';
const filesToCache = [
  '/',
  '/index.html',
  '/icon.png',
];

//install the sw
self.addEventListener('install', function (e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function (cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});


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


self.addEventListener('fetch', function (e) {
  console.log('[Service Worker] Fetch', e.request.url);
  e.respondWith(
    caches.match(e.request).then(function (response) {
      return response || fetch(e.request);
    })
  );
});

Now, We need a server to host our app. Let's create a simple express.js server. Add 'server.js' which serves the public directory.

server.js
const path = require('path');
const express = require('express');

const app = express();

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
})

app.listen(7777, function () {
  console.log('Example app listening at http://localhost:7777')
});

Project structure

How to run?
  • Install Node.js
  • Launch cmd/terminal & Navigate to the app directory and do 'npm i express' and then 'node server.js'
  • Launch your browser and visit 'localhost:7777'
  • Install the app (Click on the install button on URL Bar in case of Chrome)

Find the source for the above sample PWA here

The companies in the below pic are already delivering PWA!


Google Chat PWA
Telegram Web

Good to know about

Kindly check out my awesome-web-tech github repo for more resources.

Thanks for reading my very first article ๐Ÿ™

References

MDN, MSDN, Google Developers, web.dev, Wikipedia

Posted on by:

sudhakar3697 profile

Sudhakar RS

@sudhakar3697

Software Developer @dell. Interested in JavaScript, Node, Deno, PWA & WebAssembly.

Discussion