Created
July 3, 2014 16:36
-
-
Save tobie/113280d3b3db714dc199 to your computer and use it in GitHub Desktop.
Desired priming solution.
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.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