Progressive Web Apps

Updated: 03 September 2023

Automatically

The PWA can be built automatically using the PWABuilder

Manually

To build our app as a PWA we will need to do the following:

  1. In the index.js file, make the last line:
1
serviceWorker.register()
  1. In the serviceWorker.js file, replace the register function with the following which will register our service worker file that will be created in the next step
1
export function register(config) {
2
if ('serviceWorker' in navigator) {
3
// Use the window load event to keep the page load performant
4
window.addEventListener('load', () => {
5
navigator.serviceWorker.register('/sw.js')
6
})
7
}
8
}
  1. Create a new file called sw.js in the public directory with the following content
1
importScripts(
2
'https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js'
3
)
4
5
if (workbox) {
6
console.log(`Yay! Workbox is loaded πŸŽ‰`)
7
8
workbox.precaching.precacheAndRoute([])
9
10
workbox.routing.registerRoute(
11
/\.(?:ico|png|gif|jpg|js|css|html|svg)$/,
12
workbox.strategies.cacheFirst({
13
cacheName: 'static-cache',
14
plugins: [
15
new workbox.expiration.Plugin({
16
maxEntries: 50,
17
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
18
}),
19
],
20
})
21
)
22
23
workbox.routing.registerRoute(
24
/api\/times.*/,
25
workbox.strategies.cacheFirst({
26
cacheName: 'times-cache',
27
plugins: [
28
new workbox.expiration.Plugin({
29
maxEntries: 50,
30
maxAgeSeconds: 10 * 24 * 60 * 60,
31
}),
32
],
33
})
34
)
35
36
workbox.routing.registerRoute(
37
/api\/index.*/,
38
workbox.strategies.cacheFirst({
39
cacheName: 'index-cache',
40
plugins: [
41
new workbox.expiration.Plugin({
42
maxEntries: 50,
43
maxAgeSeconds: 10 * 24 * 60 * 60,
44
}),
45
],
46
})
47
)
48
49
// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
50
51
workbox.routing.registerRoute(
52
/^https:\/\/fonts\.googleapis\.com/,
53
workbox.strategies.staleWhileRevalidate({
54
cacheName: 'google-fonts-stylesheets',
55
})
56
)
57
58
// Cache the underlying font files with a cache-first strategy for 1 year.
59
workbox.routing.registerRoute(
60
/^https:\/\/fonts\.gstatic\.com/,
61
workbox.strategies.cacheFirst({
62
cacheName: 'google-fonts-webfonts',
63
plugins: [
64
new workbox.cacheableResponse.Plugin({
65
statuses: [0, 200],
66
}),
67
new workbox.expiration.Plugin({
68
maxAgeSeconds: 60 * 60 * 24 * 365,
69
maxEntries: 30,
70
}),
71
],
72
})
73
)
74
} else {
75
console.log(`Boo! Workbox didn't load 😬`)
76
}

This will cache all static resources and network requests to the specified endpoints

And TADA, you’re done