Created
March 2, 2015 09:05
-
-
Save petervangrieken/e44537ea428563a769f6 to your computer and use it in GitHub Desktop.
Asynchronous font loading
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
<script defer type="text/javascript"> | |
function loadCSS( href, media ){ | |
link = document.createElement( "link" ); | |
link.href = href; | |
link.type = "text/css"; | |
link.rel = "stylesheet"; | |
link.media = "only x"; | |
document.getElementsByTagName( "head" )[0].appendChild( link ); | |
var sheets = window.document.styleSheets; | |
// This function sets the link's media back to `all` so that the stylesheet applies once it loads | |
// It is designed to poll until document.styleSheets includes the new sheet. | |
function toggleMedia(){ | |
var defined; | |
for( var i = 0; i < sheets.length; i++ ){ | |
if( sheets[ i ].href && sheets[ i ].href.indexOf( href ) > -1 ){ | |
defined = true; | |
} | |
} | |
if( defined ){ | |
link.media = media || "all"; | |
} | |
else { | |
setTimeout( toggleMedia ); | |
} | |
} | |
toggleMedia(); | |
} | |
loadCSS("//cloud.typography.com/7599872/689164/css/fonts.css", "all"); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment