Skip to content

Instantly share code, notes, and snippets.

@adamhavel
Last active September 7, 2024 15:02
Show Gist options
  • 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