views:

29

answers:

2

Is there a way to not run a Javascript function until after a custom css font resource is downloaded.

I am displaying code in a <pre> and using the custom downloaded font Liberation Mono. The <pre> is also using custom scrollbars. The custom scrollbars Javascript (flexcroll) needs a static width set when setting up. But I can't know the width until the Liberation Mono font is downloaded.

The CSS to load the font is below (complete with smilie-face syntax):

@font-face {
  font-family: 'LiberationMonoRegular';
  src: url('liberationmono-regular.eot');
  src: local('☺'),
    url('liberationmono-regular.woff') format('woff'),
    url('liberationmono-regular.ttf') format('truetype'),
    url('liberationmono-regular.svg#webfontkIKtf5pm') format('svg');
  font-weight: normal;
  font-style: normal;
}

The Javascript function I would like to do is something like the following. I'm taking a shot in the dark, and really don't think this is possible..

$(function() {
    waitForFontExists('LiberationMonoRegular', function() {
        <do something>
    });
});
+2  A: 

The Google WebFont Loader project allows you to work with various web font providers, and exposes callbacks including fontloading and fontactive. This might help, depending on your flexibility with font sources. I haven't used it, but the docs state:

In addition to the google and typekit options, there is also a custom module that can load a stylesheet from any web-font provider.

Aside from this, there are much hackier things to try -- like checking the width of a sample rendering in the target font.

Ken Redler
This is very interesting. I didn't know about this package. I wonder If I can setup my own server as a web-font provider or if it's more complicated that I would like to get into. Thanks for the tip, this is why StackOverflow is awesome!
PKKid
+2  A: 

You could simply load the font file via an async XMLHTTPRequest. When the file is loaded your request object will file a ready event. This sounds inefficient but provided your font file is being cached it should only result in one additional HTTP request and a 304 response. The main downside is you couldn't really know which font formats the browser supports without browser sniffing (to my knowledge). You'd also end up downloading the font even if the user had it installed locally.

xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/path/to/font.ttf",true);
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) {
     alert("font loaded");
  }
}
xmlhttp.send(null)
SpliFF