Skip to content

Instantly share code, notes, and snippets.

@adamhavel
Last active March 21, 2016 22:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamhavel/d7c87f6dcde81a6fbd8f to your computer and use it in GitHub Desktop.
Save adamhavel/d7c87f6dcde81a6fbd8f to your computer and use it in GitHub Desktop.
(function() {
'use strict';
function getType(src) {
return src.match(/\.([^\.\?]+)(?:\?.*)?$/)[1];
}
function injectContent(content, type) {
if (type === 'css') {
var style = document.createElement('style');
document.head.appendChild(style);
style.textContent = content;
} else {
document.head.insertAdjacentHTML('beforeend', content);
}
}
window.loadFile = function(src) {
if (!window.localStorage || !window.addEventListener) {
return false;
}
var content = localStorage[src];
if (content) {
injectContent(content, getType(src));
} else {
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
localStorage[src] = xhr.responseText;
injectContent(xhr.responseText, getType(src));
});
xhr.open('GET', src);
xhr.send();
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment