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
<!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 =
alt = "GfG logo" />
< button type = "button"
onClick = "window.location.reload();" >
Refresh Page
</ button >
</ div >
</ body >
</ html >
|
- stylew.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:
Default page behaviour when connection is lost
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
<!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 =
alt = "GfG logo" />
< 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
* {
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
const offlineCache = './offline-page.html' ;
self.addEventListener( 'install' , e => {
e.waitUntil(
caches.open(offlineCache)
.then(cache => {
cache.add(offlineCache)
.then(() => self.skipWaiting())
})
);
})
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);
}
}
)
)
})
);
});
self.addEventListener( 'fetch' , e => {
console.log( 'Service Worker: Fetching' );
e.respondWith(
fetch(e.request). catch ((error) =>
caches.match(offlineCache)
)
);
});
|
- 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, GeeksForGeeks team!</ h3 >
</ div >
</ body >
</ html >
|
Losing connection reload behaviour after adding the Service Worker:
Page behaviour with service worker example code
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.
Google Chrome’s developer tools
Last Updated :
30 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...