Basic offline mode service worker on GitHub Pages

Saturday, February 16, 2019
The given example is with reference from https://googlechrome.github.io/samples/service-worker/basic/. This is a simple guide to get start with service worker for your GitHub profile page.

What does Service Worker do?

  • Precaches the HTML, JavaScript, and CSS files needed to display this page offline. (Try it out by reloading the page without a network connection!)
  • Cleans up the previously precached entries when the cache name is updated.
  • Intercepts network requests, returning a cached response when available.
  • If there's no cached response, fetches the response from the network and adds it to the cache for future use.

Lets Begin

  1.  Create a GitHub account, visit https://pages.github.com/ and follow the steps to create the site.
  2. Once your site is created make sure that SSL is enabled on the site as `navigator.serviceWorker` will not work without SSL.
  3. Prepare your Profile Page
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>John Smith</title>
    
            <!-- Bootstrap CSS -->
            <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    
            <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
            <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
            <!--[if lt IE 9]>
                <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.3/html5shiv.js"></script>
                <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
            <![endif]-->
        </head>
        <body>
            <main class="text-center">
                <br/>
                <br/>
                <br/>
                <img src="assets/img/profile.jpg" class="img-responsive center-block img-circle" alt="Profile Image">
                <h1>John Smith</h1>
                <p class="lead text-muted">This is a sample description of John</p>
                
                <button type="button" class="btn btn-success">View Résumé</button>
            </main>
            <!-- jQuery -->
            <script src="assets/js/jquery.min.js"></script>
            <!-- Bootstrap JavaScript -->
            <script src="assets/js/bootstrap.min.js"></script>
    
        </body>
    </html>
  4. Add service-worker.js to repository
    /*
     Copyright 2016 Google Inc. All Rights Reserved.
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
         http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    */
    
    // Names of the two caches used in this version of the service worker.
    // Change to v2, etc. when you update any of the local resources, which will
    // in turn trigger the install event again.
    const PRECACHE = 'precache-v1';
    const RUNTIME = 'runtime';
    
    // A list of local resources we always want to be cached.
    const PRECACHE_URLS = [
      'index.html',
      './', // Alias for index.html
      'styles.css',
      '../../styles/main.css',
      'demo.js'
    ];
    
    // The install handler takes care of precaching the resources we always need.
    self.addEventListener('install', event => {
      event.waitUntil(
        caches.open(PRECACHE)
          .then(cache => cache.addAll(PRECACHE_URLS))
          .then(self.skipWaiting())
      );
    });
    
    // The activate handler takes care of cleaning up old caches.
    self.addEventListener('activate', event => {
      const currentCaches = [PRECACHE, RUNTIME];
      event.waitUntil(
        caches.keys().then(cacheNames => {
          return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
        }).then(cachesToDelete => {
          return Promise.all(cachesToDelete.map(cacheToDelete => {
            return caches.delete(cacheToDelete);
          }));
        }).then(() => self.clients.claim())
      );
    });
    
    // The fetch handler serves responses for same-origin resources from a cache.
    // If no response is found, it populates the runtime cache with the response
    // from the network before returning it to the page.
    self.addEventListener('fetch', event => {
      // Skip cross-origin requests, like those for Google Analytics.
      if (event.request.url.startsWith(self.location.origin)) {
        event.respondWith(
          caches.match(event.request).then(cachedResponse => {
            if (cachedResponse) {
              return cachedResponse;
            }
    
            return caches.open(RUNTIME).then(cache => {
              return fetch(event.request).then(response => {
                // Put a copy of the response in the runtime cache.
                return cache.put(event.request, response.clone()).then(() => {
                  return response;
                });
              });
            });
          })
        );
      }
    });
  5. Add support for service worker to you index.html just before your ending body tag.
    <script>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('service-worker.js');
        }
    </script>
    <script src="service-worker.js"></script>
  6. Check in browser whether the offline mode works or not. Inspect you site on Chrome and go to Application tab and select Service Workers from left menu. Check whether the service-worker.js is registered or not. check the offline checkbox and refresh the page to check offline version of the page.
  7. Commit and push your changes to see whether username.github.io is working in offline mode.

Checkout the working example at https://grvsooryen.github.io/

Remember to always add your resources to service-worker.js to enable functionality in offline mode. These option enables vast opportunities to create a Progressive Web App (PWA). To further make your site to work as an app prepare your JavaScript files to use `localStorage` instead of API calls, to enable interactiveness even when offline and later on, keep the data server in sync with `localStorage`.

Please clone GitHub repository to learn more and debug the setup. 

Final Result

No comments: