moth/theme/sw.js

50 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2019-10-25 16:53:40 -06:00
var cacheName = "moth:v1"
var content = [
"index.html",
"basic.css",
"puzzle.js",
"puzzle.html",
"scoreboard.html",
"moth.js",
"sw.js",
"points.json",
2019-11-04 09:22:44 -07:00
]
2019-10-25 16:53:40 -06:00
self.addEventListener("install", function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(content).then(
function() {
2019-11-04 09:22:44 -07:00
self.skipWaiting()
})
2019-10-25 16:53:40 -06:00
})
2019-11-04 09:22:44 -07:00
)
})
2019-10-25 16:53:40 -06:00
/* Attempt to fetch live resources, first, then fall back to cache */
self.addEventListener('fetch', function(event) {
2019-11-04 09:22:44 -07:00
let cache_used = false
2019-10-25 16:53:40 -06:00
event.respondWith(
fetch(event.request)
.catch(function(evt) {
2019-11-04 09:22:44 -07:00
//console.log("Falling back to cache for " + event.request.url)
cache_used = true
return caches.match(event.request, {ignoreSearch: true})
2019-10-25 16:53:40 -06:00
}).then(function(res) {
if (res && res.ok) {
2019-11-04 09:22:44 -07:00
let res_clone = res.clone()
if (! cache_used && event.request.method == "GET" ) {
2019-10-25 16:53:40 -06:00
caches.open(cacheName).then(function(cache) {
2019-11-04 09:22:44 -07:00
cache.put(event.request, res_clone)
//console.log("Storing " + event.request.url + " in cache")
})
2019-10-25 16:53:40 -06:00
}
2019-11-04 09:22:44 -07:00
return res
2019-10-25 16:53:40 -06:00
} else {
2019-11-04 09:22:44 -07:00
console.log("Failed to retrieve resource")
2019-10-25 16:53:40 -06:00
}
})
2019-11-04 09:22:44 -07:00
)
})