brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: rel="preload" for a font only works with the crossorigin attribute

Web-Development
~/tips/tip-preload-font-crossorigin

href="/fonts/source-serif-regular.woff2"

A preloaded font arrives before the stylesheet asks for it, instead of being fetched twice.

Fonts are found late: the browser has to load the HTML, then the CSS, then notice the @font-face rule is used. Preloading the one font you need above the fold starts that download right away.

<link rel="preload"
      href="/fonts/source-serif-regular.woff2"
      as="font"
      type="font/woff2"
      crossorigin>

as="font" tells the browser what it is fetching, so it gets the right priority, and type lets a browser skip the file if it does not support the format.

The easy mistake is leaving out crossorigin because the font is on your own domain. MDN explains that fonts are always fetched in anonymous CORS mode, and the preload must use the same mode or the browser cannot reuse it. Without the attribute the font is downloaded twice: once by the preload and once by the stylesheet. I find that the most annoying kind of bug, since everything looks fine.

The href has to match the URL in your @font-face rule exactly, including any query string.

Preload only one or two files. Every preload competes for bandwidth with the HTML, CSS and images, and if the font is not used within a few seconds Chrome logs a warning in the console. Fonts for bold or italic text further down the page can wait their turn.

Further reading: MDN: rel=preload

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link