Skip to content

Instantly share code, notes, and snippets.

@mihar
Forked from jenbennings/slurpah.js
Created May 22, 2016 00:50
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 mihar/0120a2765f7f2f71c4b001596c84abca to your computer and use it in GitHub Desktop.
Save mihar/0120a2765f7f2f71c4b001596c84abca to your computer and use it in GitHub Desktop.
slurpah.js
(function(){
var externalStylesheets = [];
var fonts = {};
function findExternalStylesheets(obj, callback) {
sheet = document.styleSheets,
i = sheet.length,
rule = null;
while( 0 <= --i ) {
if (sheet[i].cssRules === null) {
obj.push(sheet[i].href);
}
}
callback();
}
function fetchStylesheets() {
externalStylesheets.forEach(loadCSSCors);
var ctr = 1;
function run_me_when_finished() {
console.log('I should load after the stylesheets have been added');
}
function loadCSSCors(stylesheet_uri) {
var _xhr = window.XMLHttpRequest;
var has_cred = false;
try {has_cred = _xhr && ('withCredentials' in (new _xhr()));} catch(e) {}
if (!has_cred) {
console.error('CORS not supported');
return;
}
var xhr = new _xhr();
xhr.open('GET', stylesheet_uri);
xhr.onload = function() {
console.log('o shit waddup');
xhr.onload = xhr.onerror = null;
if (xhr.status < 200 || xhr.status >=300) {
console.error('style failed to load: ' + stylesheet_uri)
} else {
var style_tag = document.createElement('style');
style_tag.appendChild(document.createTextNode(xhr.responseText));
document.head.appendChild(style_tag);
if (ctr === externalStylesheets.length) {
return run_me_when_finished();
}
ctr++;
};
xhr.onerror = function() {
xhr.onload = xhr.onerror = null;
console.error('XHR CORS CSS fail:' + styleURI);
};
}
xhr.send();
}
}
function getFonts(obj) {
var o = obj || {},
sheet = document.styleSheets,
rule = null,
i = sheet.length, j;
while( 0 <= --i ) {
rule = sheet[i].rules || sheet[i].cssRules || [];
j = rule.length;
while( 0 <= --j ) {
if( rule[j].constructor.name === 'CSSFontFaceRule' ) {
o[ rule[j].style.fontFamily ] = rule[j].style.src;
};
}
}
return o;
}
findExternalStylesheets(externalStylesheets, fetchStylesheets);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment