Keep a copy of your custom fonts in the user's browser, and force them to load them instead whenever possible

May 25, 2015 13:32 GMT  ·  By

Websites like The Guardian and Smashing Magazine have been using a trick to boost their pages' loading speed. It is a client-side caching system that stores Web fonts to localStorage and reuses them for subsequent visits to the site.

This approach makes the user's browser search its localStorage for the appropriate fonts every time a page is loaded, freeing up the server from answering 2-3 or more HTTP requests for custom font files.

By now, if you have any experience of working with HTML5 localStorage, you'd already be laughing at this silly solution. But if you don't have any experience with localStorage, then you're asking yourself why the other guys are laughing. The answer is: localStorage can't store complex files like fonts, handling only string-based data.

The trick is to convert the font file to base64 format and embed it in the CSS file. Yes, you read it right. You embed the font in the CSS, making one file out of two (or more).

There's a tool that can help you implement localStorage font caching

The way you can do this is by using Jaime Caballero's localFont utility, a Web-based tool that allows developers to drag&drop a font over its surface and automatically produce the CSS and JS code to implement the aforementioned font caching solution.

localFont works with WOFF, WOFF2, and TTF fonts can handle one font file at a time, and also allows developers to configure basic font style and font weight details. Once you've generated the CSS&JS code for each font, you can add them to your main CSS file and respectively the page's HTML code (for the JS).

The next time a user will access the page, the JS will check to see if the font is in his browser's localStorage, and if not, it will load it via the CSS. If the font is already cached, then the page's content is rendered with the font applied to it.

The only disadvantages to this method are a slightly heavier CSS file and a longer page load whenever users are accessing the site for the first time. Unless you're forced to work with really old browsers, support is included with all recent versions of major browsers, even with IE8.

This solution taken individually doesn't shave too many (mili)seconds off the page's total load time, but when coupled with other similar tricks like file concatenation and code compression, it helps in the long run.

There's a self-hosted version of localFont you can download via Softpedia, or you can use Jaime's version that's accessible online.