Embed Webfonts in CSS

To homepage

As you may know, you can use the Data URI Scheme to embed or inline images in css styles, instead of retrieving the image through another HTTP request:

url('data:image/png;base64,d09GRgABAAAAAGsAAA8AAAAAp...')

I wondered if you could do the same with webfonts, and it turns out to be possible. If you go to Google Webfonts and pick a font, you’ll be instructed to add a link tag that points to a Google-generated CSS documents, the contents of which look like:

@font-face {
  font-family: 'Marck Script';
  font-style: normal;
  font-weight: 400;
  src: local('MarckScript-Regular'), 
       url('http://themes.googleusercontent.com/static/fonts/marckscript/v2/O\_D1NAZVOFOobLbVtW3bcqRDOzjiPcYnFooOUGCOsRk.woff') 
       format('woff');
}

The url attribute above is pointing at a WOFF file that is hosted by Google. This means that before a site could be rendered correctly, the browser has to make another request to Google to retrieve the font file, which impacts the time until page rendering is finished. The impact will be negative if the requests are made serially. If the connections are made by the browser in parallel, then the impact is negative if:

In any case, I curled and base64’ed the URL for the Google hosted .woff file from the css fragment above:

$ curl http://themes.googleusercontent.com/static/fonts/marckscript/v2/O\_D1NAZVOFOobLbVtW3bcqRDOzjiPcYnFooOUGCOsRk.woff > MarckScript.woff
$ base64 -w0 MarkScript.woff > MarkScript.woff.b64

I copied the contents of MarkScript.woff.b64 to the url attribute of the @font-face css, and prepended some Data URI Scheme metadata:

       url('data:application/x-font-woff;base64,d09GRgABAAAAAEwMAA0AAAAAjawA.....')

And thats it, supporting browsers will now have a copy of the webfont file as soon as they load the CSS file, without the need for a separate request.