Monday, November 7, 2022
HomeWeb DevelopmentCut back cumulative structure shift in Docusaurus with fontaine

Cut back cumulative structure shift in Docusaurus with fontaine



John Reilly

MacGyver turned Dev 🌻❤️ TypeScript / ts-loader / fork-ts-checker-webpack-plugin / DefinitelyTyped: The Film



3 min learn
929

Customized font utilization can introduce cumulative structure shift (or “jank”) to your web site. This submit exhibits the right way to use fontaine to scale back this with Docusaurus websites.

What’s cumulative structure shift?

Cumulative structure shift (CLS) is a metric that measures the instability of content material on an internet web page. It’s a Core Net Vitals metric.

It’s possible you’ll nicely comprehend it as “jank”. It’s jank that you simply see when a web page masses and the textual content strikes round, and it’s a giant irritation. There’s a fantastic description of it in this submit on the subject; let me quote it right here:

Have you ever ever been studying an article on-line when one thing out of the blue adjustments on the web page? With out warning, the textual content strikes, and also you’ve misplaced your house. And even worse: you’re about to faucet a hyperlink or a button, however within the immediate earlier than your finger lands—BOOM—the hyperlink strikes, and you find yourself clicking one thing else!

This, in a nutshell, is what jank is — very irritating to finish customers and a problem that us as builders ought to attempt to keep away from as greatest we will!

For the remainder of this submit, I’ll usually to discuss with CLS as jank, because it’s a extra relatable time period.

What “jank” appears to be like like

My weblog makes use of a customized font referred to as Poppins. Pretty although it’s, utilizing the font introduces jank to my web site. It’s notably noticeable on cellphones. Right here’s a gif of the jank in motion:

My Jank Example

You see how the textual content shifts round because the customized font arrives? On the primary line we both see:

  • The fallback font rendering 4 phrases on one line: “Bicep: Static Net Apps”

…or:

  • the customized font (Poppins) rendering three phrases on one line: “Bicep: Static Net”

It’s very noticeable. So noticeable that you could truly put a quantity on it.

The quantity is the CLS rating which you’ll decide with Lighthouse. The CLS rating is the sum of the structure shifts that happen on the web page. The upper the rating, the extra jank there may be. Cumulative Structure Shift was logged as 0.019 for the web page above.

That’s not nice.

I took some steps to scale back the problems skilled, reminiscent of font preloading, however the points nonetheless remained — notably on cellular networks the place pace of loading is decreased and it takes an extended time for the customized font to load.

I had reasonably given up on bettering issues additional. However then….

fontaine

One night I used to be vaguely looking Twitter once I got here throughout a tweet from Daniel Roe which introduced a brand new device referred to as fontaine:

Screenshot Tweet About Fontaine

I used to be intrigued. I wished to attempt it out. I wished to see if it may scale back the jank on my weblog by utilizing this device.

Utilizing fontaine with Docusaurus

I added fontaine as a dependency to my weblog:

yarn add -D fontaine

I then added cracked open my docusaurus.config.js file and wrote a small plugin to utilize fontaine:

const fontaine = require('fontaine');

// ...

/** @kind {import('@docusaurus/sorts').Config} */
const config = {
  // ...

  plugins: [
    // ...
    function fontainePlugin(_context, _options) {
      return {
        name: 'fontaine-plugin',
        configureWebpack(_config, _isServer) {
          return {
            plugins: [
              fontaine.fontaineTransform.webpack({
                fallbacks: [
                  'system-ui',
                  '-apple-system',
                  'BlinkMacSystemFont',
                  'Segoe UI',
                  'Roboto',
                  'Oxygen',
                  'Ubuntu',
                  'Cantarell',
                  'Open Sans',
                  'Helvetica Neue',
                  'sans-serif',
                ],
                // It's possible you'll must resolve belongings like `/fonts/Poppins-Daring.ttf` to a selected listing
                resolvePath: (id) => '../fonts/' + id,
              }),
            ],
          };
        },
      };
    },
    // ...
  ],
  // ...
};

This didn’t initially appear to make any distinction. I put it up as a work-in-progress PR and wrote up my findings as greatest I may. Daniel was variety sufficient to have a look. He uncovered two points:

  • There was a bug in fontaine round the way it dealt with CSS variables, for which he carried out a repair
  • Docusaurus makes use of customized fonts by way of the mechanism of CSS variables. This indirection confuses fontaine as it will possibly’t learn these variables. To accommodate this, we wanted to replace my CSS variable so as to add the override font household to the CSS variable:
-  --ifm-font-family-base: 'Poppins';
+  --ifm-font-family-base: 'Poppins', 'Poppins override';

Behind the scenes, there’s a ‘Poppins override’ @font-face rule that has been created by fontaine. By manually including this override font household to our CSS variable, we make our web site use the fallback ‘Poppins override’ @font-face rule with the right font metrics that fontaine generates.

It’s price emphasizing that for the standard person of fontaine, this isn’t one thing they should do. It’s solely needed for Docusaurus customers as a result of they use customized fonts by way of CSS variables. Utilizing fontaine may be very “plug and play” for many customers.

Daniel was variety sufficient to elevate a PR incorporating each the tweaks. Once I merged that PR, I noticed the next:

My Jank Fixed

Take a look at that! You may see the font loading, however there’s no extra leaping of phrases from one line to a different. It’s an enormous enchancment from earlier than!

Conclusion

If you wish to enhance your CLS rating, fontaine is a superb device.

This submit demonstrates utilizing it with Docusaurus, however please notice that it is a usually useful gizmo that you should use with Vite, Subsequent.js, and others — it’s not particular to Docusaurus.

Previous to utilizing fontaine, my weblog’s Cumulative Structure Shift was logged as 0.019. After incorporating it, the identical rating is logged as 0. That is excellent news!

I’m very grateful to Daniel for his assist in getting it working with my weblog. He went above and past, so thanks, Daniel!

In testomony to what a fantastic thought fontaine is constructed upon; within the time I’ve been scripting this submit, @subsequent/font has been introduced, which relies upon an identical thought.

Full visibility into manufacturing React apps

Debugging React functions might be troublesome, particularly when customers expertise points which can be exhausting to breed. Should you’re fascinated by monitoring and monitoring Redux state, robotically surfacing JavaScript errors, and monitoring sluggish community requests and part load time, attempt LogRocket.

LogRocket is sort of a DVR for net and cellular apps, recording actually all the pieces that occurs in your React app. As an alternative of guessing why issues occur, you possibly can mixture and report on what state your utility was in when a problem occurred. LogRocket additionally displays your app’s efficiency, reporting with metrics like shopper CPU load, shopper reminiscence utilization, and extra.

The LogRocket Redux middleware package deal provides an additional layer of visibility into your person classes. LogRocket logs all actions and state out of your Redux shops.

Modernize the way you debug your React apps — .



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments