Created
March 11, 2016 14:37
-
-
Save jpvincent/af08d3889f00e69b1137 to your computer and use it in GitHub Desktop.
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
var namespace = window; | |
// Font Loader | |
namespace.loadFont = function(familyName, fileName, callback) { | |
var pathToFonts = 'Content/fonts/'; | |
function applyFont() { | |
var css = '@font-face { font-family: "' + familyName + '";\ | |
src: url("'+pathToFonts+ fileName + '.eot");\ | |
src: url("'+pathToFonts+ fileName + '.eot?#iefix") format("embedded-opentype"),\ | |
url("'+pathToFonts+ fileName + '.woff2") format("woff2"),\ | |
url("'+pathToFonts+ fileName + '.woff") format("woff"),\ | |
url("'+pathToFonts+ fileName + '.ttf") format("truetype");\ | |
font-weight: normal; font-style: normal;}'; | |
var style = document.createElement('style'); | |
document.getElementsByTagName('head')[0].appendChild(style); | |
style.setAttribute('rel', 'stylesheet'); | |
if ('styleSheet' in style) { | |
style.styleSheet.cssText = css; | |
} else { | |
style.appendChild(document.createTextNode(css)); | |
} | |
if (callback) | |
callback(); | |
} | |
// pour éviter le FOUT dans Fx et Chrome, on pré-charge la font si l'API FontFace existe | |
// http://caniuse.com/#feat=font-loading | |
if ('FontFace' in window) { | |
new FontFace('first', 'url('+pathToFonts+ fileName + '.woff2)', {}) | |
.load().then(applyFont); | |
// les navigateurs sans support de FontFace (IE6-11) n'ont généralement pas de FOUT, une injection directe suffit | |
} else { | |
/* body.onload : jamais de texte qui disparait, mais l'application de la font arrive très tard | |
document.body.onload = applyFont;*/ | |
// XHR : rapide, pas de texte invisible, mais il faut savoir à l'avance quelle font aller chercher | |
/*var XHR = new XMLHttpRequest(''); | |
XHR.open('GET', './'+pathToFonts+ fileName + '.woff'); | |
XHR.onload = applyFont; | |
req.send(null);*/ | |
applyFont(); | |
} | |
}; | |
loadFont('ArialBlack', 'arial-black') | |
// OU : loadFont('ArialBlack', 'arial-black', function() { | |
// console.log('application des styles possible') | |
// }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment