Tell browsers to preload fonts

When looking at Google’s PageSpeed Insights tool as part of the
compression work I noticed a suggestion that we preload our font files.
The tool suggests this should save about 300ms on first page load time.

***

Our font files are referenced from our CSS. This means that the browser
has to download and parse the CSS before it knows where to find the font
files. This means the requests happen in sequence.

We can make the requests happen in parallel by using a `<link>` tag with
`rel=preload`. This tells the browser to start downloading the fonts
before it’s even started downloading the CSS (the CSS will be the next
thing to start downloading, since it’s the next `<link>` element in the
head of the HTML).

Downloading fonts before things like images is important because once
the font is downloaded it causes the layout to repaint, and shift
everything around. So the page doesn’t feel stable until after the fonts
have loaded.

Google call this [cumulative layout shift](https://web.dev/cls/) which
is a score for how much the page moves around. A lower score means a
better experience (and, less importantly for us, means the page might
rank higher in search results)

We’re only preloading the WOFF2 fonts because only modern browsers
support preload, and these browsers also all support WOFF2.

We set an empty `crossorigin` attribute (which means anonymous-mode)
because the preload request needs to match the origin’s CORS mode. See
https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content#CORS-enabled_fetches
for more details.

We set `as=font` because this helps the browser use the correct content
security policy, and prioritise which requests to make first.
This commit is contained in:
Chris Hill-Scott
2020-12-29 13:38:27 +00:00
parent e5c34907c3
commit ea124f2886
5 changed files with 40 additions and 2 deletions

View File

@@ -89,6 +89,16 @@ class TestAssetFingerprint(object):
'app/static/application.css'
)
def test_without_hash_if_requested(self, mocker):
fingerprinter = AssetFingerprinter()
assert fingerprinter.get_url(
'application.css',
with_querystring_hash=False,
) == (
'/static/application.css'
)
assert fingerprinter._cache == {}
class TestAssetFingerprintWithUnicode(object):
def test_can_read_self(self):

View File

@@ -331,3 +331,19 @@ def test_letter_spec_redirect_with_non_logged_in_user(client_request):
'/documentation/images/notify-pdf-letter-spec-v2.4.pdf'
),
)
def test_font_preload(
client_request,
mock_get_service_and_organisation_counts,
):
client_request.logout()
page = client_request.get('main.index', _test_page_title=False)
preload_tags = page.select('link[rel=preload][as=font][type="font/woff2"][crossorigin]')
assert len(preload_tags) == 4, 'Run `npm build` to copy fonts into app/static/fonts/'
for element in preload_tags:
assert element['href'].startswith('https://static.example.com/fonts/')
assert element['href'].endswith('.woff2')