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.

  • index.html
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- 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=
                 alt="GfG logo" />
            <button type="button" 
                    onClick="window.location.reload();">
                Refresh Page
            </button>
        </div>
    </body>
      
    </html>

    chevron_right

    
    

  • stylew.css
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    /*   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_right

    
    

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
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- 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 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>

    chevron_right

    
    

  • style.css
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    /*   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_right

    
    

  • service_worker.js
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    /*  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)
            )
        );
    });

    chevron_right

    
    

  • offline-page.html
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- 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>

    chevron_right

    
    

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 developer tools

Google Chrome’s developer tools



My Personal Notes arrow_drop_up

Vice-President at the Computing Society of Edinburgh Napier University

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.