Created
July 1, 2014 18:39
-
-
Save jonathantneal/0f344639b2de6aab6fd0 to your computer and use it in GitHub Desktop.
Load and cache scripts and styles with localStorage
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 (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