Service Worker | How to create custom offline page ?
Service Workers allow to intercept the network requests and decide what to load (fetch). This feature can be used to load a custom cached offline page when the users lose connectivity, which can improve their browsing experience.
Understanding the application life-cycle
- When the user initially loads the page, the Service Worker gets installed and activated. Then the custom offline page gets stored to the browser cache.
- When the user triggers event which causes reload or navigation to another page but in the same time he is no longer connected to the internet, the service worker intercepts the network request and returns the offline cached page as a response.
Starting files
Consider that ‘index.html‘ and ‘style.css‘ are in the same folder for more simplicity.
- index.html
<!-- index.html -->
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
/>
<
meta
http-equiv
=
"X-UA-Compatible"
content
=
"ie=edge"
/>
<
link
rel
=
"stylesheet"
href
=
"./style.css"
/>
<
title
>Service Worker App</
title
>
</
head
>
<
body
>
<!-- Button causing page reload -->
<
div
class
=
"wrapper"
>
<!-- GfG logo -->
<
img
src
=
"https://media.w3wiki.net/wp-content/uploads/w3wiki-6.png"
alt
=
"GfG logo"
/>
<
button
type
=
"button"
onClick
=
"window.location.reload();"
>
Refresh Page
</
button
>
</
div
>
</
body
>
</
html
>
- stylew.css
/* style.css */
* {
margin
:
0
;
padding
:
0
;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size
:
62.5%
;
}
.wrapper {
display
: flex;
flex-
direction
: column;
justify-
content
:
center
;
align-items:
center
;
height
:
80
vh;
}
button {
padding
: .
5
rem;
font-size
:
1.5
rem;
}
Output:
Default behaviour when the user lose connectivity:
Adding the service worker:
Consider that ‘index.html‘, ‘style.css‘, ‘service-worker.js‘ and ‘offline-page.html‘ are in the same folder for more simplicity.
- index.html
<!-- index.html -->
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
/>
<
meta
http-equiv
=
"X-UA-Compatible"
content
=
"ie=edge"
/>
<
link
rel
=
"stylesheet"
href
=
"./style.css"
/>
<
title
>Service Worker App</
title
>
</
head
>
<
body
>
<
div
class
=
"wrapper"
>
<
img
src
=
"https://media.w3wiki.net/wp-content/uploads/w3wiki-6.png"
alt
=
"GfG logo"
/>
<!-- Button causing page reload -->
<
button
type
=
"button"
onClick
=
"window.location.reload();"
>
Refresh Page
</
button
>
</
div
>
<
script
>
// Check if browser supports service workers
if (navigator.serviceWorker) {
console.log("Service Worker Supported");
// Start registration process on page load
window.addEventListener("load", () => {
navigator.serviceWorker
// The register function takes as argument
// the file path to the worker's file
.register("./service_worker.js")
// Gives us registration object
.then(reg => console.log("Service Worker Registered"))
.catch(swErr => console.log(
`Service Worker Error: ${swErr}}`));
});
}
</
script
>
</
body
>
</
html
>
- style.css
/* style.css */
* {
margin
:
0
;
padding
:
0
;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size
:
62.5%
;
}
.wrapper {
display
: flex;
flex-
direction
: column;
justify-
content
:
center
;
align-items:
center
;
height
:
80
vh;
}
button {
padding
: .
5
rem;
font-size
:
1.5
rem;
}
- service_worker.js
/* service_worker.js */
const offlineCache =
'./offline-page.html'
;
// Adding the offline page
// when installing the service worker
self.addEventListener(
'install'
, e => {
// Wait until promise is finished
// Until it get rid of the service worker
e.waitUntil(
caches.open(offlineCache)
.then(cache => {
cache.add(offlineCache)
// When everything is set
.then(() => self.skipWaiting())
})
);
})
// Call Activate Event
self.addEventListener(
'activate'
, e => {
console.log(
'Service Worker - Activated'
)
e.waitUntil(
caches.keys().then(cacheNames => {
return
Promise.all(
cacheNames.map(
cache => {
if
(cache !== offlineCache) {
console.log(
'Service Worker: Clearing Old Cache'
);
return
caches.
delete
(cache);
}
}
)
)
})
);
});
// Call Fetch Event
self.addEventListener(
'fetch'
, e => {
console.log(
'Service Worker: Fetching'
);
e.respondWith(
// If there is no internet
fetch(e.request).
catch
((error) =>
caches.match(offlineCache)
)
);
});
- offline-page.html
<!-- offline-page.html-->
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
/>
<
meta
http-equiv
=
"X-UA-Compatible"
content
=
"ie=edge"
/>
<
title
>Custom Offline Page</
title
>
<
style
>
.wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 80vh;
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"wrapper"
>
<
h1
>Ooops, it looks like you lost connection.</
h1
>
<
h2
>Please check your network and try again!</
h2
>
<
h3
>Sincerely, w3wiki team!</
h3
>
</
div
>
</
body
>
</
html
>
Losing connection reload behaviour after adding the Service Worker:
How to recreate losing a connection
Almost every browser ships with built-in Developer Tools. In most of them, the shortcut to open the tools is F12 or by right clicking on the web page and selecting inspect element. Then, you can go Network and change the box ‘Online’ to ‘Offline’ and refresh your page.