Archive

Archive for August, 2009

@font-face feature detection

August 20th, 2009

As I'm piecing together a very comprehensive solution for using custom typefaces online, one of the crucial aspects is determining what browsers support @font-face.

My requirements for this detection were:

  • No browser userAgent sniffing
  • No extra HTTP request required
  • The test must be synchronous, no race conditions or HTTP requests
  • Must be performant with a small footprint, natch
  • Results should match the latest research on compatibility

I quickly tried:

!!window.CSSFontFaceRule

This test works great in FF2+, Safari and Opera. But it fails in IE (bug surprise) and Chrome gives a false positive.

The code

What follows is the best test for @font-face support I have found:

 
/*!
 * isFontFaceSupported - v0.9 - 12/19/2009
 * http://paulirish.com/2009/font-face-feature-detection/
 * 
 * Copyright (c) 2009 Paul Irish
 * MIT license
 */
 
var isFontFaceSupported = (function(){
 
 
    var fontret,
        fontfaceCheckDelay = 100;
 
		// IE supports EOT and has had EOT support since IE 5.
		// This is a proprietary standard (ATOW) and thus this off-spec,
		// proprietary test for it is acceptable. 
    if (!(!/*@cc_on@if(@_jscript_version>=5)!@end@*/0)) fontret = true;
 
    else {
 
    // Create variables for dedicated @font-face test
      var doc = document, docElement = doc.documentElement, 
          st  = doc.createElement('style'),
          spn = doc.createElement('span'),
          wid, nwid, body = doc.body,
          callback, isCallbackCalled;
 
      // The following is a font, only containing the - character. Thanks Ethan Dunham.
      st.textContent = "@font-face{font-family:testfont;src:url(data:font/opentype;base64,T1RUTwALAIAAAwAwQ0ZGIMA92IQAAAVAAAAAyUZGVE1VeVesAAAGLAAAABxHREVGADAABAAABgwAAAAgT1MvMlBHT5sAAAEgAAAAYGNtYXAATQPNAAAD1AAAAUpoZWFk8QMKmwAAALwAAAA2aGhlYQS/BDgAAAD0AAAAJGhtdHgHKQAAAAAGSAAAAAxtYXhwAANQAAAAARgAAAAGbmFtZR8kCUMAAAGAAAACUnBvc3T/uAAyAAAFIAAAACAAAQAAAAEAQVTDUm9fDzz1AAsD6AAAAADHUuOGAAAAAMdS44YAAADzAz8BdgAAAAgAAgAAAAAAAAABAAABdgDzAAkDQQAAAAADPwABAAAA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AAQAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAA/7UAMgAAAAAAAAAAAAAAAAAAAAAAAAAAAQAEBAABAQEDUEkAAQIAAQAu+BAA+BsB+BwC+B0D+BgEWQwDi/eH+dP4CgUcAIwPHAAAEBwAkREcAB4cAKsSAAMCAAEAPQA/AEFHZW5lcmF0ZWQgaW4gMjAwOSBieSBGb250TGFiIFN0dWRpby4gQ29weXJpZ2h0IGluZm8gcGVuZGluZy5QSVBJAAAAAAEADgADAQECAxQODvb3h/cXAfeHBPnT9xf90wYO+IgU+WoVHgoDliX/DAmLDAr3Fwr3FwwMHgoG/wwSAAAAAAEAAAAOAAAAGAAAAAAAAgABAAEAAgABAAQAAAACAAAAAAABAAAAAMbULpkAAAAAx1KUiQAAAADHUpSJAfQAAAH0AAADQQAA)}";
      doc.getElementsByTagName('head')[0].appendChild(st);
 
 
      spn.setAttribute('style','font:99px _,serif;position:absolute;visibility:hidden'); 
 
      if  (!body){
        body = docElement.appendChild(doc.createElement('fontface'));
      } 
 
      // the data-uri'd font only has the - character
      spn.innerHTML = '-------';
      spn.id        = 'fonttest';
 
      body.appendChild(spn);
      wid = spn.offsetWidth;
 
      spn.style.font = '99px testfont,_,serif';
 
      // needed for the CSSFontFaceRule false positives (ff3, chrome, op9)
      fontret = wid !== spn.offsetWidth;
 
      var delayedCheck = function(){
        if (isCallbackCalled) return;
        fontret = wid !== spn.offsetWidth;
        callback && (isCallbackCalled = true) && callback(fontret);
      }
 
      addEventListener('load',delayedCheck,false);
      setTimeout(delayedCheck,fontfaceCheckDelay);
    }
 
    function ret(){  return fontret || wid !== spn.offsetWidth; };
 
    // allow for a callback
    ret.ready = function(fn){
      (isCallbackCalled || fontret) ? fn(fontret) : (callback = fn);
    }  
 
    return ret;
})();

Download from github

The latest is always at: http://github.com/paulirish/font-face-detect
isFontFaceSupported.js Uncompressed – 4.3k
isFontFaceSupported.min.js Compressed – 3.1k

Usage

isFontFaceSupported() // will return a boolean indicating support
 
// you can also use with a callback,
//  it will be called 100ms later which is adaquate for Gecko and Webkit to properly use the data-uri'd font.
isFontFaceSupprted.ready(function(bool){
  // bool is a boolean that indicates support
});

Sorry. :(

You'll spot the IE conditional compilation in there. I don't like it either, but I'm unaware of any other workable approach (that doesn't pull in an .eot) to test for @font-face support. If you have an idea, please share it!

On the approach

I first use the Web Font Optimizer to subset a truetype font to only contain the period (.) character (2.2k file!), then send it through a data URI converter, then chuck it into a style tag. I test the width of a span of text without the custom font, and then again with the custom font. If the values are different, we can assume @font-face is supported and works.

With a trip through the YUI Compressor, the script is 3.5k3.1k. If you have any ideas on bringing that figure down, I'd love to hear 'em.

Great! Any disadvantages?

Yeah there's one big one. Both Gecko and Webkit load in a data-uri font asynchronously, so the test may give a false negative if you call isFontFaceSupported() immediately afterwards:

<script src="isFontFaceSupported.min.js"></script>
<script>
  if (isFontFaceSupported()) ... // this may report a false negative.
 // that's why we have the isFontFaceSupported.ready() callback mechanism

I'm not terribly happy with this asynchronous delay, so I've written an alternative that uses browser userAgent sniffing. This practice is not recommended and is not terribly future-proof, but it's the only synchronous solution available.

isFontFaceSupported() – sniffing variant
/*!
 * isFontFaceSupported - Sniff variant - v0.9 - 12/19/2009
 * http://paulirish.com/2009/font-face-feature-detection/
 * 
 * Copyright (c) 2009 Paul Irish
 * MIT license
 */
 
/* Browser sniffing is bad. You should use feature detection.
   Sadly the only feature detect for @font-face is 
   asynchronous. So for those that *need* a synchronous solution,
   here is a sniff-based result:
*/
 
var isFontFaceSupported = function(){
 
  var ua = navigator.userAgent, parsed;
 
  if (/*@cc_on@if(@_jscript_version>=5)!@end@*/0) 
      return true;
  if (parsed = ua.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/))
      return parsed[1] >= '4.0.249.4';
  if ((parsed = ua.match(/Safari\/(\d+\.\d+)/)) && !/iPhone/.test(ua))
      return parsed[1] >= '525.13';
  if (/Opera/.test({}.toString.call(window.opera)))
      return opera.version() >= '10.00';
  if (parsed = ua.match(/rv:(\d+\.\d+\.\d+)[^b].*Gecko\//))
      return parsed[1] >= '1.9.1';    
 
  return false;
 
}

This guy is also on github

2009.09.24: updated the code, and threw it all on github. callback style makes its debut here. This code matches the exact same implementation that's in Modernizr 1.0

2009.12.18: Added a useragent sniffing alternative for those who want reliable synchronous detection.

2009.12.19: New, smaller font file (Thanks Ethan Dunham). The file is now 15% smaller. Script does not remove the extra element it adds to the DOM now, as to assure more accurate results.

2010.11.02: I now recommend a different technique.. It's from Diego Perini.. The code is below:
var isFontFaceSupported = (function(){  
var 
sheet, doc = document,
head = doc.head || doc.getElementsByTagName('head')[0] || docElement,
style = doc.createElement("style"),
impl = doc.implementation || { hasFeature: function() { return false; } };
 
style.type = 'text/css';
head.insertBefore(style, head.firstChild);
sheet = style.sheet || style.styleSheet;
 
var supportAtRule = impl.hasFeature('CSS2', '') ?
        function(rule) {
            if (!(sheet && rule)) return false;
            var result = false;
            try {
                sheet.insertRule(rule, 0);
                result = !(/unknown/i).test(sheet.cssRules[0].cssText);
                sheet.deleteRule(sheet.cssRules.length - 1);
            } catch(e) { }
            return result;
        } :
        function(rule) {
            if (!(sheet && rule)) return false;
            sheet.cssText = rule;
 
            return sheet.cssText.length !== 0 && !(/unknown/i).test(sheet.cssText) &&
              sheet.cssText
                    .replace(/\r+|\n+/g, '')
                    .indexOf(rule.split(' ')[0]) === 0;
        };
 
return supportAtRule('@font-face { font-family: "font"; src: "font.ttf"; }');
})();

Paul Irish front-end development, javascript, typography

.net magazine – may issue

August 17th, 2009

Back in the May issue of .net magazine, my friend and talented designer Tom Kershaw wrote an article on improving your speed, efficiency and polish with Photoshop. [PDF download here]

I wrote a sidebar about better ways for front-end developers to work with visual designers. Funnily enough, because of the lead time, by the time the magazine got to press, some of my recommendations (e.g. "embrace sIFR") were already out of date.

If anyone has additional recommendations on how front-end developers and designers can improve their workflow, I'd love to see them in the comments.

Paul Irish me

Caching and Google's Ajax Libraries API — Cache your jQuery

August 14th, 2009

Leveraging Google's free hosting of common javascript libraries seems to be getting more popular. While you should be serving all javascript concatenated and minified together, the free hosting is nice for quick jobs or more minimal projects.

The versioning system they devised is a very clever way to always serve you the most up-to-date script. For example, you request version 2 of SWFObject and it'll currently deliver 2.2, but in the future you'll always get the most recent 2.x release.

I did a bit of research on how they handle these cases, and since these facts aren't elsewhere, they needed a home. :)

The current caching rules are as follows:

Request Response cached for
/1.3.2/jquery.min.js one year
/1.3/jquery.min.js no caching
/1/jquery.min.js one hour

* jQuery URLs used only for illustration purposes. It's the same case with all scripts' minor/major versions
* Minified and unminified files are treated the same

Previous to now, using the google.load('jquery','1.2.6') technique was the only way to ensure the script stayed considerably cached. Direct path-based access scripts were only cached for one day. But no worries, because all is better now.

2010.08.25 – Updated caching times. How odd..

Paul Irish front-end development

Debounced resize() jQuery plugin

August 11th, 2009

If you've ever attached an event handler to the window's resize event, you have probably noticed that while Firefox fires the event slow and sensibly, IE and Webkit go totally spastic.

PPK lays it out like this:

  • In IE, Safari, and Chrome many resize events fire as long as the user continues resizing the window.
  • Opera uses as many resize events, but fires them all at the end of the resizing.
  • Firefox fires one resize event at the end of the resizing.

When I first saw John Hann's debounce post, this use case is what I immediately thought of.

This isn't exactly throttling, but it's close. Basically debouncing will fire your function after a threshold of time (e.g. 100ms) has elapsed since the last time it's tried to fire. Throttling would withhold subsequent firings, but debouncing waits for the last one and runs that.

Take a look at the difference on the demo.

The code for smartresize:

(function($,sr){
 
  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;
 
      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null; 
          };
 
          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);
 
          timeout = setTimeout(delayed, threshold || 100); 
      };
  }
	// smartresize 
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
 
})(jQuery,'smartresize');
 
 
// usage:
$(window).smartresize(function(){  
  // code that takes it easy...
});

Pretty straightforward stuff. What else do you think would be an appropriate use of debounce()?

Paul Irish jquery

The direction forward with web fonts

August 11th, 2009
Comments Off

In the current discussions around fonts on the web, there is much confusion between the techniques. Most seem to think that TypeKit and .webfont are our only options. They are not, but the rest of the landscape is quite busy.

Things have been moving very quickly in the last three weeks, so let me break it down like this:

  • Webfont services: TypeKit, fontdeck, Typotheque
  • Proposals: EOT-Lite, .webfont, ZOT, webOTF
  • Implemented standards: @font-face using EOT and TTF
  • JavaScript-based font solutions: sIFR, Facelift, Cufón

The commercial webfont services players

While many have considered TypeKit as an alternative to .webfont, it's just a smart implementation of CSS and JavaScript along with a shop and licensing model. I agree with Pablo Impallari who commented:

You don’t need typekit, .webfont or any other solution. You can start using real fonts on the web right now.

Typekit makes a somewhat complicated implementation drop-dead easy, but if you've used sIFR before, than I'm confident you can handle this on your own.

The licensing legwork that TypeKit is doing is a significant value-add and may be worth it for people who don't want to deal directly with font resellers. I'm quite interested in how the smart folks at Clearleft expect to differentiate their competing service, fontdeck.

Typotheque and Kernest are also new entrants to watch, both created by font shops. Both seem to only license their own foundries' typefaces, so their library size may end up being quite small, but I can say right now Typotheque's offering looks strong.

At the same time, we've had web font services already: Fontburner and Flir Premium, but they never really gained popularity, so I'm surprised people expect such a different outcome from these new players.

The EOT-Lite and .webfont proposals

The general complaint from the type community around non-EOT @font-face is that the naked font is so accessible, anyone could trivially take it off a webserver and install it on their machine. These two proposals offer a “garden fence” approach to protection; it's still quite easy to get inside and snag the font, but it's harder than if there were no protection at all.

.webfont, the format proposed by Tal Leming and Erik van Blokland is a great compromise solution: basically a zip file containing both an xml file of metadata and the font. While it uses the same css @font-face syntax, and everyone seems to love it, having it work in all browsers is at least three years off.

EOT-Lite, on the other hand, seems to be covered much less in roundups to date. The basic idea is that it's the same as EOT but without the two major complaints of the format: domain binding and MTX compression. (Interesting as, the compression's patent owner is offering to free it up.)

The huge plus of EOT-Lite is that the format works, right now, in IE4-IE8. Adobe, Monotype, Microsoft and a cadre of type shops support it. Perhaps surprising for some, Mozilla is also quite involved in the EOT-Lite discussion, not only helping to define the spec, but also making a test build of Firefox that handles the new format.

ZOT is a new format proposed by Mozilla; essentially TTF with compression. It's well considered, but as .webfont comes with the same advantages and already has a wave of support, I think ZOT is best left as an academic discussion. Oh, and Berlow's OpenType permissions table – which would have been a great idea to have in 2000, but not now.

Update 2009.08.10: .webfont and ZOT merged their proposals. It's now called WebOTF.

The @font-face standard

By my calculations, the current implementation (using EOT or TTF/OTF) covers ~70% of users. When Firefox 3.0 users upgrade to 3.5 that figure will increase to ~90% of users (I bet we'll see that within six months). Things still do visually look a little different across browser implementations, but they currently work cross-browser and with fixes like forcing Cleartype on for web fonts in Firefox, render quality is improving steadily.

/* it's this easy: */
@font-face {
  font-family: 'Gentium';
  src: url(Gentium.eot); /* EOT for IE */
}
@font-face {
  font-family: 'Gentium';
  /* IE ignores this one because of the format value */
  src: url(Gentium.ttf) format("opentype");
}
h1,h2,h3 { font-family: 'Gentium', Tahoma, sans-serif;

I generally side with the concerns of type foundries here, rather than the Fuck The Foundries crowd. I want myself and other designers to have access to the best of typography, but understand the fonts used for Firefox/Webkit are a little too naked at this point. While we're waiting for the rest of this to pan out we may see a new market of type designers that are comfortable with naked fonts (like David B?ezina), but I'm skeptical about the efficacy of that.

JavaScript-based custom font solutions

We've had sIFR for nearly 5 years and I'm glad we have, but we now have better options. After significant research I think Cufón is the best library in this space; it's small, clever, and very performant. However, many foundries aren't ready to license their typefaces for use with Cufon. Facelift is a great alternative here, as it doesn't expose the font data to the browser (instead generating PNGs via PHP), thus very licensing-friendly.


These libraries will be useful in bringing custom fonts to older browsers (currently: Firefox 3.0, Chrome, and Opera 9), but still lack flexibility when it comes to rtl languages.

It's also possible that they won't be treated only as a fallback solution. If foundries remain unwilling to license for the naked @font-face implementation in Firefox and Webkit, we may have no choice but to use Cufón while we're waiting for these browsers to adopt EOT-Lite or .webfont. In fact, Monotype's web embedding EULA currently allows use with siFR and Cufón, as long as there is domain-binding.

Conclusions

I don't think webfont services are the future, but I do think the landscape is hairy enough now to convince web developers to take the easy route by relying on a TypeKit or Fontdeck for their custom type. Taking advantage of the best techniques available isn't insurmountable without a hosted webfont service, and I think we'll see developers going it alone with their own implementations and licensing directly with the font resellers.

I believe EOT-Lite is the right direction for webfonts right now. It already works in the most stubborn browser, and since Firefox just released a test build with support for EOT-Lite, it's looking more reasonable than ever. It's also quite interesting that after the months of debate at the W3C surrounding Microsoft's proposal of making EOT the standard, it took quite some time for the sensible proposal of EOT-Lite to emerge. I guess both sides had to soften a little. :)

This is a cross-post, originally appearing on Molecular Voices. If you have any comments or questions, please leave a comment there.

Paul Irish front-end development, typography

i left this space here for you to play. <3