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><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><metahttp-equiv="X-UA-Compatible"content="ie=edge"/><linkrel="stylesheet"href="./style.css"/><title>Service Worker App</title></head><body><!-- Button causing page reload --><divclass="wrapper"><!-- GfG logo --><imgsrc=alt="GfG logo"/><buttontype="button"onClick="window.location.reload();">Refresh Page</button></div></body></html>chevron_rightfilter_none - 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:80vh;}button {padding: .5rem;font-size:1.5rem;}chevron_rightfilter_none
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
<!-- index.html --><!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><metahttp-equiv="X-UA-Compatible"content="ie=edge"/><linkrel="stylesheet"href="./style.css"/><title>Service Worker App</title></head><body><divclass="wrapper"><imgsrc=alt="GfG logo"/><!-- Button causing page reload --><buttontype="button"onClick="window.location.reload();">Refresh Page</button></div><script>// Check if browser supports service workersif (navigator.serviceWorker) {console.log("Service Worker Supported");// Start registration process on page loadwindow.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>chevron_rightfilter_none - 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:80vh;}button {padding: .5rem;font-size:1.5rem;}chevron_rightfilter_none - service_worker.js
/* service_worker.js */const offlineCache ='./offline-page.html';// Adding the offline page// when installing the service workerself.addEventListener('install', e => {// Wait until promise is finished// Until it get rid of the service workere.waitUntil(caches.open(offlineCache).then(cache => {cache.add(offlineCache)// When everything is set.then(() => self.skipWaiting())}));})// Call Activate Eventself.addEventListener('activate', e => {console.log('Service Worker - Activated')e.waitUntil(caches.keys().then(cacheNames => {returnPromise.all(cacheNames.map(cache => {if(cache !== offlineCache) {console.log('Service Worker: Clearing Old Cache');returncaches.delete(cache);}}))}));});// Call Fetch Eventself.addEventListener('fetch', e => {console.log('Service Worker: Fetching');e.respondWith(// If there is no internetfetch(e.request).catch((error) =>caches.match(offlineCache)));});chevron_rightfilter_none - offline-page.html
<!-- offline-page.html--><!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><metahttp-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><divclass="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>chevron_rightfilter_none
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
Recommended Posts:
- How to create a custom callback in JavaScript?
- How to create fade-in effect on page load using CSS ?
- How to create footer to stay at the bottom of a Web page?
- Create a database on Relational Database Service (RDS) of Amazon Web Services(AWS)
- How to display search result of another page on same page using ajax in JSP?
- How to redirect a page to another page in HTML ?
- How to show Page Loading div until the page has finished loading?
- Bootstrap 4 | Custom Forms
- Service Workers in Javascript
- $timeout service in AngularJS
- Deploying Your Web App using Azure App Service
- JavaScript | Creating a Custom Image Slider
- Creating custom domain name instead of localhost in Ubuntu
- Python | User groups with Custom permissions in Django
- Google Geo-coding Web Service (JSON response)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



