Enable font-display on Google Fonts with Cloudflare Workers

Pier-Luc Gendreau
Sep 23, 2018 · 2 min read

I have posted an improved iteration which is significantly faster! Check out how to supercharge Google Fonts with Cloudflare and Service Workers 🚀

While Google Fonts is quite fast out of the box, Google’s own web page auditing tool, Lighthouse, has been (justifiably!) nagging developers to improve performance by enabling font-display. Unfortunately, this isn’t currently supported out of the box and has been an issue for over two years.

“time lapse photography of northbound and southbound lane” by David Becker on Unsplash

What’s important to keep in mind is that Google is actually quite smart about serving fonts. In addition to great caching, it will respond with the most appropriate format for a given browser. Knowing that, some smart folks have implemented a clever workaround: fetching fonts in JavaScript and manually patching in the font-display property.

Just a few days ago, Addy Osmani mentioned Google is currently exploring how to best implement a solution. Meanwhile, what if we could solve this ourselves?

Cloudflare to the rescue

Announced almost a year ago, Cloudflare Workers enable running JavaScript on the edge using an API similar to Service Workers. This means we can use it as a serverless proxy to add font-display to Google Fonts while being remaining completely transparent to the application.

Here is a simplified version of the worker I use for Jirafe:

Whenever requests come in from fonts.jirafe.io, they are immediately forwarded to fonts.googleapis.com and, once a response is received, it adds in font-display to every @font-face declarations, instantly improving time to first meaningful paint.

I feel like this is one of many powerful use cases for Cloudflare Workers and it has been working very well for Jirafe, waiting for fonts to load was the last big hurdle to allowing the (admittedly simple) page to load incredibly fast even on mobile devices.

Pier-Luc Gendreau

Written by

🦄 JavaScript Developer at Classcraft 🚀 Creating Jirafe, a Slack bot for Jira 🦒