Last active
August 29, 2015 14:03
-
-
Save tobie/0689c5dda8f6d49d500d to your computer and use it in GitHub Desktop.
Priming the cache when there's a cache miss.
This file contains 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
this.oninstall = function(e) { | |
// Create a cache of resources. | |
var resources = new Cache(); | |
var visited = new Cache(); | |
// Fetch them. | |
e.waitUntil(resources.add( | |
"/index.html", | |
"/fallback.html", | |
"/css/base.css", | |
"/js/app.js", | |
"/img/logo.png" | |
).then(function() { | |
// Add caches to the global caches. | |
return Promise.all([ | |
caches.set("v1", resources), | |
caches.set("visited", visited) | |
]); | |
})); | |
}; | |
this.onfetch = function(e) { | |
e.respondWith( | |
// Check to see if request is found in cache | |
caches.match(e.request).catch(function() { | |
// It's not? Prime the cache and return the response. | |
return caches.get("visited").then(function(visited) { | |
return visited.add(e.request).then(function() { | |
return visited.match(e.request); | |
}); | |
}); | |
}).catch(function() { | |
// Connection is down? Simply fallback to a pre-cached page. | |
return caches.match("/fallback.html"); | |
}); | |
); | |
}; |
This file contains 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
this.oninstall = function(e) { | |
// Create a cache of resources. | |
var resources = new Cache(); | |
var visited = new Cache(); | |
// Fetch them. | |
e.waitUntil(resources.add( | |
"/index.html", | |
"/fallback.html", | |
"/css/base.css", | |
"/js/app.js", | |
"/img/logo.png" | |
).then(function() { | |
// Add caches to the global caches. | |
return Promise.all([ | |
caches.set("v1", resources), | |
caches.set("visited", visited) | |
]); | |
})); | |
}; | |
this.onfetch = function(e) { | |
e.respondWith( | |
// Check to see if request is found in cache | |
caches.match(e.request).catch(function() { | |
// It's not? Prime the cache and return the response. | |
return caches.get("visited").then(function(visited) { | |
return fetch(e.request).then(function(response) { | |
visited.put(e.request, response); | |
// Don't bother waiting, respond already. | |
return response; | |
}); | |
}); | |
}).catch(function() { | |
// Connection is down? Simply fallback to a pre-cached page. | |
return caches.match("/fallback.html"); | |
}); | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment