Skip to content

Instantly share code, notes, and snippets.

@petervangrieken
Created March 2, 2015 09:05
Show Gist options
  • Save petervangrieken/e44537ea428563a769f6 to your computer and use it in GitHub Desktop.
Save petervangrieken/e44537ea428563a769f6 to your computer and use it in GitHub Desktop.
Asynchronous font loading
<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