Need a Progressive Web App for your business?
Contact Us

Build offline website using service worker

Build offline website using service worker to make your website run without internet. We share some sample code to cache your assets and other files.

Posted by Vivek on 05 Feb 2019
Build offline website using service worker

Service Worker is Javascript running on a separate thread than the usual browser Javascript thread. This provides various features possible like Push notification, Background Sync, making website run offline by using caching options.

Install Service Worker

Add sw.js on the root path of your website - yourwebsite.com/sw.js.

// sw.js
// Cache versions
// Change this when you deploy any JS change
var CACHE_NAME = "cache-01-02-2019-001"

// Remove cache due to browser caching limit
function trimCache(cacheName, maxItems) {
  caches.open(cacheName).then(function (cache) {
    return cache.keys().then(function (keys) {
      if (keys.length > maxItems) {
        cache.delete(keys[0]).then(trimCache(cacheName, maxItems))
      }
    })
  })
}

// Event listener for Service Worker installation
// This event can be used to cache files on first load of website
self.addEventListener("install", function (event) {
  console.log("[Service Worker] Installing Service Worker ...", event)
  event.waitUntil(
    caches.open(CACHE_STATIC_NAME).then(function (cache) {
      console.log("[Service Worker] Precaching App Shell")
      cache.addAll(STATIC_FILES)
    })
  )
})

// Event listener for Service Worker activation
self.addEventListener("activate", function (event) {
  console.log("[Service Worker] Activating Service Worker ....", event)
  event.waitUntil(
    caches.keys().then(function (keyList) {
      return Promise.all(
        keyList.map(function (key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_NAME) {
            console.log("[Service Worker] Removing old cache.", key)
            return caches.delete(key)
          }
        })
      )
    })
  )
  return self.clients.claim()
})

self.addEventListener("fetch", function (event) {
  // If request is html, store in cache. If network and cache are not
  // found, then return the home page
  if (event.request.headers.get("accept").includes("text/html")) {
    event.respondWith(
      fetch(event.request)
        .then(function (response) {
          return caches.open(CACHE_NAME).then(function (cache) {
            cache.put(event.request.url, response.clone())
            return response
          })
        })
        .catch(function (error) {
          return caches.match(event.request).then(function (response) {
            if (response) {
              return response
            } else {
              return caches.match("/")
            }
          })
        })
    )
    // Don't store images in caches to save space in cache
  } else if (event.request.headers.get("accept").includes("image")) {
    event.respondWith(fetch(event.request))
    // Cache other request
  } else {
    event.respondWith(
      caches.match(event.request).then(function (response) {
        if (response) {
          return response
        } else {
          return fetch(event.request)
            .then(function (res) {
              return caches.open(CACHE_NAME).then(function (cache) {
                trimCache(CACHE_NAME, 20)
                cache.put(event.request.url, res.clone())
                return res
              })
            })
            .catch(function (err) {
              // handle no catch for other assets
            })
        }
      })
    )
  }
})

That's it, install the above file in your website and see it run offline.

Contact us to work on making your website work offline.

More links -
Google PWA
Hire us for building progressive web app.

Vivek


Need a Progressive Web App for your business?
Contact Us

Related Services.



Hire ReactJS Developers
Hire Gatsby Developers
Hire NextJS Developers

We support the Open Source community.



Have a Project in mind?