Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toBlogCacheAPI

How to add cache to your site to make it available offline

It is really simple to add some cache to your site in order to make it available offline.

It should be a Jamstack or a simple static site that solely relies on some static files alone.

Introduce Service Worker

If the browser supports it, register our sw.js first.

if ('serviceWorker' in navigator) {
.register('/sw.js', { scope: '/' })
.then(function (registration) {
console.log('Service Worker Registered')
navigator.serviceWorker.ready.then(function (registration) {
console.log('Service Worker Ready')

By default it works under the loaded context ('/' - here) but we can also specify the same using the config object while registering { scope: '/' }.

Write sw.js with caching options

const version = '1';
const cacheName =`site-cache-${version}`;
// Opens the cache on SW install event.
self.addEventListener('install', (e) => {
e.waitUntil( => {
// Add all of static needed to run the site.
return (
'[email protected]/css/tachyons.min.css',
// Just update it right away.
.then(() => self.skipWaiting())
self.addEventListener('activate', (event) => {
// Claim for all the clients to start using it right away.
self.addEventListener('fetch', (event) => {
// Intercept all fetch and return with cache when available.
.then((cache) => cache.match(event.request, { ignoreSearch: true }))
.then((response) => {
return response || fetch(event.request)

You can also add your UI frame libs to the cache as well.