Created
February 13, 2017 02:10
-
-
Save johngerome/8d9c5b5ab0ad04346fb20fa91c389dde to your computer and use it in GitHub Desktop.
non-blocking fonts by caching it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to encode a font into Base64 use this tool https://www.npmjs.com/package/font-store | |
(function (window, document) { | |
'use strict'; | |
var isModernBrowser = ( | |
'querySelector' in document && | |
'localStorage' in window && | |
'addEventListener' in window | |
), | |
key = 'font', | |
fonts = [{ | |
'name': 'titillium_web', | |
'md5': '64a81399f2d31c3a555baea86bceb4d7' | |
}, | |
{ | |
'name': 'source_sans_pro', | |
'md5': '9f7c6e5f1ee953a86d0f1ed92f20c599' | |
}, | |
], | |
cache; | |
if (!isModernBrowser) { | |
// Sorry, browser is too old! | |
return; | |
} | |
function insertFont(value) { | |
var style = document.createElement('style'); | |
style.innerHTML = value; | |
document.head.appendChild(style); | |
} | |
function storeFonts(font) { | |
window.addEventListener('load', function () { | |
var request = new XMLHttpRequest(), | |
response; | |
request.open('GET', '/assets/fonts/fonts.' + font.md5 + '.json', true); | |
request.onload = function () { | |
if (this.status == 200) { | |
try { | |
response = JSON.parse(this.response); | |
insertFont(response.value); | |
window.localStorage.setItem(key + '_' + font.name, this.response); | |
} catch (e) { | |
// LocalStorage is probably full | |
} | |
} | |
}; | |
request.send(); | |
}); | |
} | |
try { | |
for (var i = 0; i < fonts.length; i++) { | |
cache = JSON.parse(window.localStorage.getItem(key + '_' + fonts[i].name)); | |
if (cache !== null && cache.md5 === fonts[i].md5) { | |
insertFont(cache.value); | |
} else { | |
// Busting cache when md5 doesn't match | |
window.localStorage.removeItem(key + '_' + fonts[i].name); | |
storeFonts(fonts[i]); | |
} | |
} | |
} catch (e) { | |
// Most likely LocalStorage disabled, so hopeless... | |
console.warn(e); | |
return; | |
} | |
})(window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
credits to http://crocodillon.com/blog/non-blocking-web-fonts-using-localstorage. i just modified his code to allow multiple fonts.