Fastest way to Google Fonts
Harry Roberts writes about fastest ways of loading Google fonts on his blog:
It’s widely accepted that self-hosted fonts are the fastest option: same origin means reduced network negotiation, predictable URLs mean we can preload, self-hosted means we can set our own cache-control directives, and full ownership mitigates the risks that come with leaving static assets on third-party origins.
That said, the convenience of a service like Google Fonts cannot be overstated. Their ability to serve the tiniest possible font files tailored to specific user agents and platforms is amazing, and with such a huge, freely-available library served from Google-grade CDNs… I definitely see why people continue to turn to it.
Well, yes. Self hosting fonts is a pain. Can we make it a little faster with the CDN?
Harry dives into a private instance of Webpage test and marks the performance metrics for each attribute that can be used. Here is what he ends up doing:
1<!--2 - 1. Preemptively warm up the fonts’ origin.3 -4 - 2. Initiate a high-priority, asynchronous fetch for the CSS file. Works in5 - most modern browsers.6 -7 - 3. Initiate a low-priority, asynchronous fetch that gets applied to the page8 - only after it’s arrived. Works in all browsers with JavaScript enabled.9 -10 - 4. In the unlikely event that a visitor has intentionally disabled11 - JavaScript, fall back to the original method. The good news is that,12 - although this is a render-blocking request, it can still make use of the13 - preconnect which makes it marginally faster than the default.14 -->1516<!-- [1] -->17<link rel="preconnect"18 href="https://fonts.gstatic.com"19 crossorigin />2021<!-- [2] -->22<link rel="preload"23 as="style"24 href="$CSS&display=swap" />2526<!-- [3] -->27<link rel="stylesheet"28 href="$CSS&display=swap"29 media="print" onload="this.media='all'" />3031<!-- [4] -->32<noscript>33 <link rel="stylesheet"34 href="$CSS&display=swap" />35</noscript>
We can find a sample to this on Harry’s site:
1<!-- [1] -->2<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">34<!-- [2] -->5<link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,900;1,900&family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap">67<!-- [3] -->8<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,900;1,900&family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap" media="all" onload="this.media='all'">
On to the fast lane! 👏👏