Progressive Web Apps (PWA)

WIP

Lighthouse

Chrome dev tools -> Lighthouse to run an audit

  • analyzes performace, accessibility, seo and determines if your app is installable as a PWA. Test at https://fireship.io/
  • Trigger and test push notifications, background sync of the service worker

Workbox

Library to help build PWA’s

  • Cache URL’s in your app so they can be viewed offline. Inspect the cache under chrome dev tools Application tab under Cache Storage. Example at https://fireship.io/

If using React or Angular

1
npm install workbox-cli --global

or import from CDN

1
importScripts('cdn://workbox-sw.js')

PWA Components

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF=8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Hello World</title>
<link rel="icon" href="/favicon.ico">
<link rel="manifest" href="manifest.json">
</head>
<body>
<h1>Hello World</h1>
<script>
if ('serviceWorker' in navigation) {
navigation.serviceWorker.register('/service-worker.js');
}
</script>
</body>
</html>

logo.png

Your logo bro \ :D /

manifest.json

  • manifest.json

Contains icons and other meta data about the app.

Icons can be created with PWA Asset generator, this will target logo.png and output the results in the icons directory. Additionally this will produce the content needed for the mainifest.json file (look in the terminal output)

1
npx pwa-asset-generator logo.png icons

Example from https://fireship.io/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"name": "Fireship.io",
"short_name": "Fireship.io",
"description": "Awesome Content for App Developers",
"start_url": ".",
"display": "standalone",
"background_color": "#2a2e35",
"theme_color": "#454e56",
"icons": [
{
"src": "/img/favicon.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "/img/logo-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

service-worker.js

Enable caching networkFirst() will use network first but fall back to cacheFirst is the network is not avalible.

1
2
3
4
5
6
7
8
9
10
11
12
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.0.2/workbox-sw.js');

if (workbox) {

workbox.routing.registerRoute(
({request}) => request.destination === 'image',
workbox.strategies.cacheFirst()
);

} else {
console.log(`Browser not supported`);
}
1
npx serve

If you are using the Create react app tool will automatically generate a service worker for you.

Service worker -> register to run in the background.

  • Caching pages
  • Run background sync
  • Listen for push notifications

This will check if the browser supports the feature and then reginster the worker which is service-worker.js.

Once registered it can be seen in the Application tab in chrome dev tools.

References

2