Google Workbox: get your first PWA app going in a few minutes!

Creating fast mobile websites just became easier!

PWA (Progressive Web App) is slowly becoming a base technology for modern websites.

Google has started to push PWA implementation for websites by making Mobile website speed as one of the signals for SEO rankings.

To simplify implementation and remove cumbersome PWA JS implementations, they created a framework / library called Workbox.

You will need to create two files: manifest.json, serviceworker.js, logo-192.png, logo-512.png. You also need to create an offline page (/offline) to render on web app in case your client or website goes offline.

 

Here is code you need to get started with your first PWA app.

Put this at the top of your <head> and </head> tags:

 

1
2
3
4
5
// colour of your theme on mobile devices
<meta name='theme-color' content='#363636'>

// link to your manifest file
<link rel='manifest' href='/manifest.json'>

 
and
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
// ServiceWorker is a progressive technology. Ignore unsupported browsers
if ('serviceWorker' in navigator) {
    console.log('CLIENT: service worker registration in progress.');
    navigator.serviceWorker.register('/serviceworker.js').then(function () {
        console.log('CLIENT: service worker registration complete.');
        //registration.update();
    }, function () {
        console.log('CLIENT: service worker registration failure.');
    });
} else {
    console.log('CLIENT: service worker is not supported.');
}
</script>

 

Then we need to add manifest.json:

Manifest.json (how to use)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "short_name": "SHORT NAME OF YOUR SITE",
  "name": "example.com",
  "description": "Description of your website",
  "icons": [
    {
      "src": "/logo-192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/logo-512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/?utm_source=sw",
  "background_color": "#cdcccc",
  "display": "fullscreen",
  "scope": "/",
  "theme_color": "#f7f6ef"
}

 

NOTES:

start_url: is your starting URL when you install your web app on your mobile device

background_colour: background of loading page of your web app

display: how to display your web app on your mobile device

scope: url scope of your web app

 

Lastly we need to add manifest.json:

Serviceworker.js (how to use)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.2.0/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded);
 
    // Default cache names for your app.
    workbox.core.setCacheNameDetails({
      prefix: 'example-app',
      suffix: 'v1',
      precache: 'install-time',
      runtime: 'run-time',
      googleAnalytics: 'ga',
    });
   
    // Pre-caching of your most used urls for faster page loading
    // Here we pre-chache App home page, offline page, style.css and app.js. These are usually the static files that do not change all the time.
    workbox.precaching.precacheAndRoute([
        { url: '/?utm_source=sw', revision: 'v1' },
        { url: '/offline', revision: 'v1' },
        { url: '/css/style.css', revision: 'v1' },
        { url: '/js/app.js', revision: 'v1' }
    ])

    // Caching of your CSS files as you go through the website (some pages have more css files, some less).
    // "The stale-while-revalidate pattern allows you to respond the request as quickly as possible with a cached response if available, falling back to the network request if it’s not cached".
    workbox.routing.registerRoute(
        // Cache CSS files.
        /\.css$/,
        // Use cache but update in the background.
        new workbox.strategies.StaleWhileRevalidate({
          // Use a custom cache name.
          cacheName: 'css-cache',
        })
    );

    // Caching of your JS files as you go through the website (some pages have more JS files, some less).
    // "The stale-while-revalidate pattern allows you to respond the request as quickly as possible with a cached response if available, falling back to the network request if it’s not cached".
    workbox.routing.registerRoute(
        // Cache JS files.
        /\.js$/,
        // Use cache but update in the background.
        new workbox.strategies.NetworkFirst({
          // Use a custom cache name.
          cacheName: 'js-cache',
        })
    );
   
    // Image caching into browser. This allows you to cache your images into the browser in case your web app or user goes offline.
    workbox.routing.registerRoute(
        // Cache image files.
        /\.(?:png|jpg|jpeg|svg|gif|woff2)$/,
        // Use the cache if it's available.
        new workbox.strategies.CacheFirst({
          // Use a custom cache name.
          cacheName: 'image-cache',
          plugins: [
            new workbox.expiration.Plugin({
              // Cache only 100 images.
              maxEntries: 100,
              // Cache for a maximum of a week.
              maxAgeSeconds: 7 * 24 * 60 * 60,
            })
          ],
        })
    );
   
    // Caching pages that you need to make sure stay online. They will get cached for offline use.
    workbox.routing.registerRoute(/\/.|\/portfolio./,
    async ({event}) => {
        try {
          return await workbox.strategies.staleWhileRevalidate({
              cacheName: 'general-cache-pages'
          }).handle({event});
        } catch (error) {
          return caches.match('/offline');
        }
      }
    );
 
} else {
  console.log(`Boo! Workbox didn't load);
}

 

There you go, you should be able to use and install your web app right away.

If you are having issues, try using Audit section of Chrome (right click, Inspect, Audit). It will tell you if your web app is PWA ready.

PS: here are results from using PWA on my site:

 
Paulmade.me Page Speed Insights with Google Workbox PWA

Leave a Reply