Created
March 5, 2012 17:36
-
-
Save marcuswestin/1979651 to your computer and use it in GitHub Desktop.
Custom font loading
This file contains hidden or 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
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