Skip to content

Instantly share code, notes, and snippets.

@marcuswestin
Created March 5, 2012 17:36
Show Gist options
  • Save marcuswestin/1979651 to your computer and use it in GitHub Desktop.
Save marcuswestin/1979651 to your computer and use it in GitHub Desktop.
Custom font loading
module.exports = {
load:load
}
function load(callback) {
var testEl = document.createElement('span')
testEl.style.fontFamily = 'sans-serif';
testEl.innerHTML = 'TEST_STRING'
testEl.style.visibility = 'hidden'
testEl.style.position = 'absolute'
testEl.style.bottom = 0
document.body.appendChild(testEl)
var originalWidth = testEl.offsetWidth
var link = document.createElement('link')
link.rel = 'stylesheet'
link.type = 'text/css'
link.href = 'https://fonts.googleapis.com/css?family=Lobster'
document.getElementsByTagName('head')[0].appendChild(link)
setTimeout(function() {
// Give the browser a chance to lay things out with the original font first
testEl.style.fontFamily = 'Lobster, sans-serif';
})
var intervalID = setInterval(testForFont)
if (testForFont()) { return callback() }
setTimeout(onDone)
function testForFont() {
if (testEl.offsetWidth == originalWidth) { return }
onDone()
}
function onDone() {
if (testEl.parentNode == document.body) { document.body.removeChild(testEl) }
clearInterval(intervalID)
callback()
}
}
// curl http://fonts.googleapis.com/css?family=Lobster
// curl http://fonts.googleapis.com/css?family=Lobster -A "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment