Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active February 27, 2017 02:07
Show Gist options
  • Save martynchamberlin/586f6938ef8ce0146a03b8300c59b776 to your computer and use it in GitHub Desktop.
Save martynchamberlin/586f6938ef8ce0146a03b8300c59b776 to your computer and use it in GitHub Desktop.
How to conditionally load Google Font client-side while avoiding FOUT
<html>
<head>
<script>
/**
* This function used with gratitude from
* http://stackoverflow.com/a/34666534/1591507
* I want to refactor this to ES6 so badly but
* since it has to reside in the DOM to avoid FOUT,
* we can't transpile with Babel unfortunately
*/
function addCss(fileName) {
var head = document.head
, link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = fileName
head.appendChild(link)
}
// Wrap this call with any sort of conditional you like
addCss('http://fonts.googleapis.com/css?family=Open+Sans:400,600,700&subset=latin,latin-ext');
</script>
<style>
h1 {
font-family: 'Open Sans';
}
</style>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment