Skip to content

Instantly share code, notes, and snippets.

@ahmedam55
Last active April 25, 2019 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedam55/173d076bcfc5aa42e83902ebc8393fc7 to your computer and use it in GitHub Desktop.
Save ahmedam55/173d076bcfc5aa42e83902ebc8393fc7 to your computer and use it in GitHub Desktop.
Service Worker: Serve from Cache, then revalidate the Cache After Specific Time
<html>
<head>
<link rel="stylesheet" href="/style.css">
</head>
<body>
PWA: Stale-while-revalidate: xx
<script src="/script.js"></script>
</body>
</html>
console.log('PWA - Main Script')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./xyz.js')
}
const cacheName = 'xyz'
const filesToCache = ['/script.js', 'style.css', '/']
const blob = (data = {}) => new Blob([JSON.stringify(data)], { type: 'application/json' })
const init = { status: 200, statusText: 'success' }
const lastFetchedTimeRequest = new Request(blob(), init)
const cacheExpirationDurationMs = 10000
const updateCachedLastFetchedTime = cache => {
cache.put(lastFetchedTimeRequest, new Response(blob({ date: new Date() }), init))
}
const getLastFetchedTime = cache => {
return cache
.match(lastFetchedTimeRequest)
.then(result => result.json())
.then(json => new Date(json.date))
}
const precache = event => {
event.waitUntil(
caches.open(cacheName).then(cache => {
cache.addAll(filesToCache)
updateCachedLastFetchedTime(cache)
}),
)
}
const getCacheAndUpdate = event => {
event.respondWith(
caches.open(cacheName).then(cache => {
return cache.match(event.request).then(response => {
getLastFetchedTime(cache).then(date => {
const lastFetchedTime = date.getTime()
const now = new Date().getTime()
const timeSinceLastFetch = now - lastFetchedTime
const secondsSinceLastFetch = Math.round(timeSinceLastFetch / 1000)
const tenSecondsHavePassed = timeSinceLastFetch >= cacheExpirationDurationMs
console.log(`${secondsSinceLastFetch}s passed since last fetch`)
if (tenSecondsHavePassed) {
fetch(event.request).then(response => {
cache.put(event.request, response)
console.log('refetched')
updateCachedLastFetchedTime(cache)
})
}
})
return response
})
}),
)
}
self.addEventListener('install', precache)
self.addEventListener('fetch', getCacheAndUpdate)
body {
margin: 20px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment