public
Last active

Playing with implementing AppCache through the NavigationController

  • Download Gist
controller.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
var fallbacks = {}
, networks = {}
, cacheName = "OldSchoolAppCache"
;
 
this.onmessage = function (e) {
var msg = e.data;
if (msg.type && msg.type === "manifest") {
var lines = msg.manifest.split(/\n+/)
, mode = "cache"
, hadCache = false
, cache
;
if (cache = this.caches.get(cacheName)) {
hadCache = true;
}
else {
cache = new Cache();
}
// this is not the real parsing algorithm
if (lines.shift() !== "CACHE MANIFEST") return;
while (lines.length) {
var line = lines.shift();
if (line.match(/(?:^\s*$)|(?:^\s*#.*$)/)) continue;
var directive = line.match(/^(CACHE|NETWORK|FALLBACK):$/);
if (directive) {
mode = directive.toLowerCase();
continue;
}
line = line.replace(/(^\s+|\s+$)/g, "");
if (mode === "cache") {
cache.add(line);
}
else if (mode === "fallback") {
var parts = line.split(/\s+/, 2);
fallbacks[parts[0]] = parts[1];
}
else {
networks[line] = true;
}
}
if (!hadCache) this.caches.set(cacheName, cache);
}
};
 
// we don't handle wildcards, but that's a detail
this.onrequest = function (e) {
var cache = this.caches.get(cacheName);
if (networks[e.request.url]) return; // hit the network
if (fallbacks[e.request.url] && !this.onLine) {
var res = cache.match(fallbacks[e.request.url]);
if (res) {
e.preventDefault();
e.respondWith(res);
return;
}
}
};
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<!DOCTYPE html>
<html manifest="foo.manifest" controller="controller.js" controllerpath="/*">
<head>
<script>
if (document.documentElement.hasAttribute("manifest")) {
window.controller.ready().then(function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", document.documentElement.getAttribute("manifest"));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
window.controller.postMessage({ type: "manifest", manifest: xhr.responseText});
}
};
xhr.send();
});
}
</script>
</head>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.