Open In App

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



  1. 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.
  2. 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.



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.

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


Article Tags :