Created
June 16, 2014 21:13
-
-
Save ef4/82f37eb5dae4e56467b6 to your computer and use it in GitHub Desktop.
Example Application Cache "Bootloader"
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
(function(){ | |
function useManifest(content){ | |
var tag; | |
var stylesheets = content.match(/\/css\/.*\.css/g); | |
for (var i=0; i<stylesheets.length; i++){ | |
tag = document.createElement('link'); | |
tag.href = stylesheets[i]; | |
tag.rel = "stylesheet"; | |
document.getElementsByTagName('head')[0].appendChild(tag); | |
} | |
var scripts = content.match(/\/js\/.*\.js/g); | |
var loadedCount = 0; | |
function didLoad(){ | |
loadedCount += 1; | |
if (loadedCount == scripts.length){ | |
var global = (function(){return this;})(); | |
global.bootloadedManifest = { | |
scripts: scripts, | |
stylesheets: stylesheets, | |
body: content | |
}; | |
require('main'); | |
} | |
} | |
for (i=0; i<scripts.length; i++) { | |
// This is where you can choose to skip over certain Javascript files | |
// that appear in the manifest -- in this case, a web worker runtime | |
if (/\bworker\b/.test(scripts[i])){ | |
loadedCount +=1; | |
} else { | |
tag = document.createElement('script'); | |
tag.src = scripts[i]; | |
tag.type = "text/javascript"; | |
tag.onload = didLoad; | |
document.getElementsByTagName('head')[0].appendChild(tag); | |
} | |
} | |
} | |
function retrieveManifest(cb){ | |
var req = new XMLHttpRequest(); | |
req.open("GET",document.documentElement.getAttribute('manifest'),true); | |
req.onreadystatechange = function(){ | |
if (req.readyState === req.DONE){ | |
if (req.status === 200){ | |
cb(req.response); | |
} else { | |
throw new Error("failed to retrieve manifest"); | |
} | |
} | |
}; | |
req.send(); | |
} | |
// In development, you don't want to be running out of an actual | |
// application cache, because you need to reload all the time. But | |
// we do want to test everything under the bootloader. So this lets | |
// you provide a fake manifest file within a <script type="text/fake-manifest"> | |
// tag. | |
function retrieveFakeManifest(cb){ | |
var content = document.querySelector('script[type="text/fake-manifest"]').innerHTML; | |
if (content) | |
cb(content); | |
else | |
throw new Error("no fake manifest available"); | |
} | |
if (document.documentElement.getAttribute('manifest')){ | |
retrieveManifest(useManifest); | |
} else { | |
retrieveFakeManifest(useManifest); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks promising. Have you had many use cases where appcache was very useful in these modern times where internet is readily available?