Skip to content

Instantly share code, notes, and snippets.

@XhmikosR
Forked from adamhavel/loadFile
Last active August 29, 2015 14:07
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 XhmikosR/fd60b8ada51367b0d2c2 to your computer and use it in GitHub Desktop.
Save XhmikosR/fd60b8ada51367b0d2c2 to your computer and use it in GitHub Desktop.
(function() {
'use strict';
var files = ['assets/site/css/non-critical.css', 'assets/site/img/icons.svg'];
function getExtension(src) {
return src.split('.').pop();
}
function onEvent(el, event, callback) {
if (el.addEventListener) {
el.addEventListener(event, callback);
} else if (el.attachEvent) {
el.attachEvent('on' + event, callback);
}
}
function injectContent(content, type) {
if (type === 'css') {
var style = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
if (style.styleSheet) {
style.styleSheet.cssText = content;
} else {
style.innerHTML = content;
}
} else if (type === 'svg') {
document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', content);
}
}
function loadFile(file) {
var content = localStorage[file];
if (content) {
injectContent(content, getExtension(file));
} else {
onEvent(window, 'load', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', file, true);
onEvent(xhr, 'load', function() {
if (xhr.readyState === 4) {
injectContent(xhr.responseText, getExtension(file));
localStorage[file] = xhr.responseText;
}
});
xhr.send();
});
}
}
if (window.localStorage) {
for (var i = 0, count = files.length; i < count; i++) {
if (getExtension(files[i]) === 'svg' && !document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1')) {
return;
}
loadFile(files[i]);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment