Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created July 1, 2014 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/0f344639b2de6aab6fd0 to your computer and use it in GitHub Desktop.
Save jonathantneal/0f344639b2de6aab6fd0 to your computer and use it in GitHub Desktop.
Load and cache scripts and styles with localStorage
(function (NAME, LISTENER, HEAD) {
window[NAME] = function (src, node, loading) {
var
// prepare cache
key = NAME + ':' + src,
cache = localStorage[key] || '',
name = parseFloat(cache[0]) ? 'script' : 'style',
x, xhr;
// if cache exists
if (cache) {
// append cache
x = document.createElement('x');
x.innerHTML = '<' + name + '>' + cache.slice(1) + '</' + name + '>';
if (node) HEAD.removeChild(node);
node = x.lastChild;
HEAD.appendChild(node);
}
// if document is ready
if (/t/.test(document.readyState) && !loading) {
// load resource
xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.onload = function () {
// save resource to cache
localStorage[key] = (/javascript|json/.test(xhr.getResponseHeader('content-type')) ? 1 : 0) + xhr.responseText;
// rerun
window[NAME](src, node, true);
};
xhr.send();
} else {
// rerun on window load
window[LISTENER[0]](LISTENER[1] + 'load', function () {
window[NAME](src);
});
}
};
})(
'cache',
'addEventListener' in window ? ['addEventListener', ''] : ['attachEvent', 'on'],
document.getElementsByTagName('head')[0]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment