Skip to content

Instantly share code, notes, and snippets.

@adamhavel
Last active Mar 21, 2016
Embed
What would you like to do?
(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