Using a CDN (Content Delivery Network) to serve your Rails assets can go a long way in speeding up your site and cutting down on bandwidth costs, but it does comes with added complexity when serving fonts.
In order to use a font hosted on a different domain, your font should be returned with the appropriate CORS headers, otherwise the browser will refuse to use them.
We always seem to spend a while getting this all set-up with Cloudfront (which is reallygood at caching) - even when followingtested recipes - but we wanted a workaround without CORS headers so that clients and QA could test sites in development with the proper fonts in place.The solution
Firstly, if you're using a free font (e.g. from Google Fonts), you should have no problem. For other free fonts - like Font Awesome - there are several free CDNs you can slot into your <head>tag.
Otherwise, you'll need to customise the config.asset_hostsetting for your Rails application. As well as taking a URL string, you can also set this to a Proc, which will be evaluated for each asset when requested (i.e. when using one of the asset pipeline URL/path helpers).
We have to be careful to distinguish SVGs, since they could either be fonts or images. In practice, we've found that the filename is sufficient (see FONT_FILE_REGEXabove) to distinguish fonts, since SVGs generally only come from the asset pipeline (and not user uploads), and we can thus be confident that all SVG filenames are under our control.
Since Sprockets caches individual files (to speed up asset precompilation), you may find you have to change the CSS/Sass file that includes the @font-facestatement(s) - or clear your cache - in order for the correct URL to the font file(s) to be generated.
One last gotcha to be aware of is that domain matching for CORS is exact- in other words, cross-domain restrictions apply even between subdomains. This is why both fonts and the CSS file(s) that refer them have to come from the same exact domain.Conclusion
I hope this workaround helps while getting everything set-up on your app. Now, I'm off to do battle with rack-cors...
Photo by Daniel Ullrich on Flickr