Last active
June 11, 2020 19:21
-
-
Save kumarasinghe/bbfe69a9f9a1cd0d8ee5d2a676d92147 to your computer and use it in GitHub Desktop.
Service Worker Template Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CACHE_VERSION = 'cache-v1' // increment this when you update the web site | |
const filesToCache = [ | |
"./index.html", | |
"./path/an/image.png", | |
// add more static assets to cache | |
] | |
self.addEventListener( | |
'install', | |
function (event) { | |
// start caching assets | |
console.log('Installing service worker...') | |
event.waitUntil( | |
// open a new cache space | |
caches.open(CACHE_VERSION) | |
.then(function (cache) { | |
return cache.addAll(filesToCache) | |
}) | |
) | |
}) | |
self.addEventListener( | |
'activate', | |
async function (event) { | |
event.waitUntil( | |
// delete any other cache which is not the current version | |
self.caches.keys().then(function (cacheKeys) { | |
cacheKeys.forEach(function (cacheKey) { | |
if (cacheKey != CACHE_VERSION) { | |
self.caches.delete(cacheKey) | |
} | |
}) | |
return true | |
}) | |
) | |
} | |
) | |
self.addEventListener( | |
'fetch', | |
function (event) { | |
event.respondWith( | |
// check cache for a response | |
caches.match(event.request) | |
.then(async function (cachedResponse) { | |
// try to serve with cache first | |
if (cachedResponse) { | |
return cachedResponse | |
} | |
// else try to serve from network | |
try { | |
let freshResponse = await fetch(event.request) | |
if (freshResponse) { | |
return freshResponse | |
} | |
} | |
// show offline page if server is not reachable | |
catch (error) { | |
var offlinePageResponse = new Response( | |
'', | |
{ | |
status: 302, | |
statusText: 'Found', | |
headers: { | |
Location: '/offline.html' | |
} | |
} | |
) | |
return offlinePageResponse | |
} | |
}) | |
) | |
} | |
) | |
console.log('Service Worker loaded!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment