Skip to content

Instantly share code, notes, and snippets.

@tobie
Created July 3, 2014 16:36
Show Gist options
  • Save tobie/113280d3b3db714dc199 to your computer and use it in GitHub Desktop.
Save tobie/113280d3b3db714dc199 to your computer and use it in GitHub Desktop.
Desired priming solution.
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.put(e.request, fetch(e.request));
});
}).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