Skip to main content

Preload fonts with Docusaurus

· 3 min read

When we're using custom fonts in our websites, it's good practice to preload the fonts to minimise the flash of unstyled text. This post shows how to achieve this with Docusaurus. It does so by building a Docusaurus plugin which makes use of Satyendra Singh's excellent webpack-font-preload-plugin

title image reading "Preload fonts with Docusaurus" in a ridiculous font with the Docusaurus logo and a screenshot of a preload link HTML element

Preload web fonts with Docusaurus

To quote the docs of the webpack-font-preload-plugin:

The preload value of the <link> element's rel attribute lets you declare fetch requests in the HTML's <head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance.

This plugin specifically targets fonts used with the application which are bundled using webpack. The plugin would add <link> tags in the begining of <head> of your html:

<link rel="preload" href="/font1.woff" as="font" crossorigin />
<link rel="preload" href="/font2.woff" as="font" crossorigin />

If you want to learn more about preloading web fonts, it's also worth reading this excellent article.

The blog you're reading is built with Docusaurus. Our mission: for the HTML our Docusaurus build pumps out to feature preload link elements. Something like this:


This link element has the rel="preload" attribute set, which triggers font preloading.

But the thing to take from the above text is that the filename features a hash in the name. This demonstrates that the font is being pumped through the Docusaurus build, which is powered by webpack. So we need some webpack whispering to get font preloading going.

Making a plugin

We're going to make a minimal Docusaurus plugin using webpack-font-preload-plugin. Let's add it to our project:

yarn add webpack-font-preload-plugin

Now in the docusaurus.config.js we can create our minimal plugin:

const FontPreloadPlugin = require('webpack-font-preload-plugin');

/** @type {import('@docusaurus/types').Config} */
const config = {
plugins: [
function preloadFontPlugin(_context, _options) {
return {
name: 'preload-font-plugin',
configureWebpack(_config, _isServer) {
return {
plugins: [new FontPreloadPlugin()],
// ...

It's a super simple plugin, it does nothing more than new up an instance of the webpack plugin, inside the context of the configureWebpack method. That's all that's required.

With this in place we're now seeing the <link rel="preload" ... /> elements being included in the HTML pumped out of our Docusaurus build. This means we have font preloading working:

screenshot of the Chrome devtools featuring link rel=&quot;preload&quot; elements