With the growing popularity of web fonts, it’s quite common to use 3rd-party providers, like Google Fonts or Typekit, to integrate custom fonts into your site. When it comes to performance, fonts can make a significant impact on a page. So if you’re using a 3rd-party provider, here are two quick tips that can help lessen the impact.
<link>
not @import
Most providers will give you a few options for using their fonts, and usually the two primary ones are to use <link>
or @import
.
For instance, if you’re using Roboto from Google Fonts, you could include
@import url('https://fonts.googleapis.com/css?family=Roboto');
in your stylesheet, or you could include
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
in your markup.
Under normal circumstances, you’ll want to use the <link>
. This allows the request to run in parallel with the main CSS file. Otherwise, if the @import
is included in your stylesheet, the request to the 3rd-party site won’t start until after the main file has been downloaded, which just delays the downloading of the actual fonts from the provider.
So if you’re currently using @import
in a stylesheet, making the simple switch to a <link>
in the header could easily get you a small performance boost.
Use the preconnect
hint
In cases where you know which domain you’ll be connecting to, you can use the preconnect
hint to tell the browser to connect to the server in the background, including DNS lookups, TLS negotiations, and TCP handshakes. Doing this removes costly roundtrips when the browser is actually ready to download the needed resource(s) from that domain.
When it comes to fonts from 3rd-parties, you may not always know the exact file name for the resources, but it’s very possible that you’ll know the domain. For instance, if you knew for certain that you were going to be using Google Fonts to host a font, you could use
<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
in the page header to make sure the browser connects to the domain as early as possible. That way, when it’s time to download the fonts, there’s no additional delay.
Using preconnect saves you some roundtrips later on, allowing you to download the necessary fonts earlier.
Two notes about using preconnect
:
-
Current support includes Firefox and Chrome, but thankfully, Safari and iOS Safari are looking to add support in their upcoming releases (11.1 and 11.3).
-
Don’t forget to add the
crossorigin
attribute in the link. This is necessary when using thepreconnect
hint for loading fonts.
Every little bit helps
Now, the ultimate performance enhancement would be to trim down the number of custom fonts to as few as possible. But getting that number to zero may not be possible in your situation. If that’s the case, and you’re using a 3rd-party, the above tips can at lease alleviate some of the performance impact that these fonts are bound to have.