Skip to content

Instantly share code, notes, and snippets.

@shinypb
Forked from darobin/controller.js
Last active December 12, 2015 07:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinypb/4739368 to your computer and use it in GitHub Desktop.
Save shinypb/4739368 to your computer and use it in GitHub Desktop.
var fallbacks = {}
, networks = {}
, cacheName = "OldSchoolAppCache"
, settings = {}
;
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|SETTINGS):$/);
if (directive) {
mode = directive.toLowerCase();
continue;
}
line = line.replace(/(^\s+|\s+$)/g, "");
switch (mode) {
case 'cache':
cache.add(line);
break;
case 'fallback':
var parts = line.split(/\s+/, 2);
fallbacks[parts[0]] = parts[1];
break;
case 'settings';
settings[line] = true;
break;
default: // network
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 (settings['prefer-online'] && this.onLine) 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>
@slightlyoff
Copy link

Would like to check this into the repo. Objections?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment