Skip to content

Instantly share code, notes, and snippets.

@darobin
Last active December 12, 2015 07:48
Show Gist options
  • Save darobin/4739167 to your computer and use it in GitHub Desktop.
Save darobin/4739167 to your computer and use it in GitHub Desktop.
Playing with implementing AppCache through the NavigationController
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;
}
}
};
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment