Skip to content

Instantly share code, notes, and snippets.

@ahmedam55

ahmedam55/index.html

Last active Apr 25, 2019
Embed
What would you like to do?
Service Worker: Cache then Update Strategy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Service Worker</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Test service worker cache and update
<img src="https://image.flaticon.com/icons/svg/1164/1164951.svg" alt="crescent smiling">
<script src="/script.js"></script>
</body>
</html>
console.log('Test')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js')
}
body {
font-size: 20px;
}
img {
width: 10px;
}
var cacheName = 'cache-and-update'
var filesToCache = [location.origin + '/script.js', location.origin + '/style.css', location.origin]
var getCache = function(callback) {
return caches.open(cacheName).then(callback)
}
var precache = function(event) {
event.waitUntil(
getCache(function(cache) {
return cache.addAll(filesToCache)
}),
)
}
var updateCache = function(cache, request) {
fetch(request).then(function(response) {
return cache.put(request, response)
})
}
const arrayContains = (array, text) => {
const result = array.filter(fileToCache => text.indexOf(fileToCache) > -1).length > 0
return result
}
var fromCacheAndUpdate = function(event) {
// if you don't respondWith it'd be a no-op for the service worker
if (arrayContains(filesToCache, event.request.url)) {
event.respondWith(
getCache(function(cache) {
return cache.match(event.request).then(function(response) {
var notInFilesToCache = response
if (notInFilesToCache) {
updateCache(cache, event.request)
return response
} else {
return fetch(event.request)
}
})
}),
)
}
}
self.addEventListener('install', function(event) {
precache(event)
})
self.addEventListener('fetch', function(event) {
fromCacheAndUpdate(event)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment