Skip to content

Instantly share code, notes, and snippets.

@Igloczek
Created August 28, 2015 15:43
Show Gist options
  • Save Igloczek/8196dd756e8b547ce964 to your computer and use it in GitHub Desktop.
Save Igloczek/8196dd756e8b547ce964 to your computer and use it in GitHub Desktop.
Localstorage font loader with WOFF2 support and fallback to older browsers (like IE8)
<!--[if !IE]><!-->
<script type="text/javascript">
var supportsWoff2 = (function(){
if(!('FontFace' in window)){
return false;
}
var f = new window.FontFace( "t", 'url("data:application/font-woff2,") format("woff2")', {});
f.load().catch(function(){});
return f.status === 'loading';
})();
</script>
<!--<![endif]-->
<script type="text/javascript">
function loadFonts(fontName){
"use strict";
var fontsUrl = "<?php echo Mage::getDesign()->getSkinUrl('fonts') ?>",
isModernBrowser = (
'querySelector' in document &&
'localStorage' in window &&
'addEventListener' in window &&
'XMLHttpRequest' in window
);
function injectStyles(cssText) {
var head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if(style.sheet){ // for IE9+
style.innerHTML = cssText;
style.sheet.cssText = cssText;
head.appendChild(style);
}
else if(style.styleSheet){ // for IE8
head.appendChild(style);
style.styleSheet.cssText = cssText;
}
else{
style.innerHTML = cssText;
style.appendChild(document.createTextNode(cssText));
head.appendChild(style);
}
}
if(isModernBrowser){
if(typeof localStorage[fontName] !== 'undefined'){
injectStyles(window.localStorage[fontName]);
}
else{
var fontUrl = {};
if(typeof supportsWoff2 !== 'undefined' && supportsWoff2){
fontUrl = fontsUrl + '/woff2/' + fontName + '.css';
}
else{
fontUrl = fontsUrl + '/woff/' + fontName + '.css';
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
injectStyles(xhr.responseText);
localStorage[fontName] = xhr.responseText;
}
};
xhr.open("GET", fontUrl, true);
xhr.send();
}
}
else{
var cssText = "@font-face {" +
"font-family: '" + fontName + "';" +
"src: url('" + fontsUrl + "/src/" + fontName + ".eot');" +
"src: url('" + fontsUrl + "/src/" + fontName + ".eot?#iefix') format('embedded-opentype')," +
"url('" + fontsUrl + "/src/" + fontName + ".woff2') format('woff2')," +
"url('" + fontsUrl + "/src/" + fontName + ".woff') format('woff')," +
"url('" + fontsUrl + "/src/" + fontName + ".ttf') format('truetype')," +
"url('" + fontsUrl + "/src/" + fontName + ".svg#" + fontName + "') format('svg');" +
"font-weight: normal;" +
"font-style: normal;" +
"};";
injectStyles(cssText);
}
}
loadFonts('Roboto');
loadFonts('Roboto-light');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment