Web-Design
Monday January 11, 2021 By David Quintanilla
Front-End Performance Checklist 2021 — Smashing Magazine


Is internet font supply optimized?
The primary query that’s price asking is that if we will get away with using UI system fonts within the first place — we simply want to verify to double check that they appear correctly on varied platforms. If it’s not the case, chances are high excessive that the online fonts we’re serving embody glyphs and further options and weights that aren’t getting used. We will ask our kind foundry to subset internet fonts or if we’re utilizing open-source fonts, subset them on our personal with Glyphhanger or Fontsquirrel. We will even automate our total workflow with Peter Müller’s subfont, a command line instrument that statically analyses your web page with the intention to generate essentially the most optimum internet font subsets, after which inject them into our pages.

WOFF2 support is nice, and we will use WOFF as fallback for browsers that don’t help it — or maybe legacy browsers may very well be served system fonts. There are many, many, many choices for internet font loading, and we will select one of many methods from Zach Leatherman’s “Comprehensive Guide to Font-Loading Strategies,” (code snippets additionally accessible as Web font loading recipes).

In all probability the higher choices to think about in the present day are Critical FOFT with preload and “The Compromise” method. Each of them use a two-stage render for delivering internet fonts in steps — first a small supersubset required to render the web page quick and precisely with the online font, after which load the remainder of the household async. The distinction is that “The Compromise” approach masses polyfill asynchronously provided that font load events should not supported, so that you don’t have to load the polyfill by default. Want a fast win? Zach Leatherman has a quick 23-min tutorial and case study to get your fonts so as.

On the whole, it is perhaps a good suggestion to make use of the preload useful resource trace to preload fonts, however in your markup embody the hints after the hyperlink to vital CSS and JavaScript. With preload, there’s a puzzle of priorities, so contemplate injecting rel="preload" components into the DOM simply earlier than the exterior blocking scripts. In line with Andy Davies, “sources injected utilizing a script are hidden from the browser till the script executes, and we will use this behaviour to delay when the browser discovers the preload trace.” In any other case, font loading will price you within the first render time.

A screenshot of slide 93 showing two example of images with a title next to them saying ‘Metrics prioritization: preload one of each family’
When all the pieces is vital, nothing is vital. preload just one or a most of two fonts of every household. (Picture credit score: Zach Leatherman – slide 93) (Large preview)

It’s a good suggestion to be selective and select information that matter most, e.g. those which can be vital for rendering or that may assist you avoiding seen and disruptive textual content reflows. On the whole, Zach advises to preload one or two fonts of every household — it additionally is sensible to delay some font loading if they’re much less vital.

It has turn into fairly frequent to make use of native() worth (which refers to a lo­cal font by identify) when defining a font-family within the @font-face rule:

/* Warning! Not a good suggestion! */
@font-face {
  font-family: Open Sans;
  src: native('Open Sans Common'),
       native('OpenSans-Common'),
       url('opensans.woff2') format ('woff2'),
       url('opensans.woff') format('woff');
}

The thought is affordable: some in style open-source fonts resembling Open Sans are coming pre-installed with some drivers or apps, so if the font is avail­in a position lo­cally, the browser does­n’t have to down­load the online font and may dis­play the lo­cal font im­me­di­ately. As Bram Stein noted, “although a lo­cal font matches the identify of an online font, it most probably isn’t the identical font. Many internet fonts dif­fer from their “desk­high” ver­sion. The textual content is perhaps ren­dered dif­fer­ently, some char­ac­ters might fall again to different fonts, Open­Kind fea­tures could be miss­ing en­tirely, or the road peak could also be dif­fer­ent.”

Additionally, as typefaces evolve over time, the domestically put in model is perhaps very totally different from the online font, with characters wanting very totally different. So, in accordance with Bram, it’s higher to by no means combine lo­cally in­stalled fonts and internet fonts in @font-face guidelines. Google Fonts has adopted swimsuit by disabling local() on the CSS results for all users, apart from Android requests for Roboto.

No person likes ready for the content material to be displayed. With the font-display CSS descriptor, we will management the font loading conduct and allow content material to be readable instantly (with font-display: non-compulsory) or virtually instantly (with a timeout of 3s, so long as the font will get efficiently downloaded — with font-display: swap). (Properly, it’s a bit more complicated than that.)

Nonetheless, if you wish to minimize the impact of text reflows, we may use the Font Loading API (supported in all modern browsers). Particularly which means for each font, we’d creata a FontFace object, then attempt to fetch all of them, and solely then apply them to the web page. This manner, we group all repaints by loading all fonts asynchronously, after which swap from fallback fonts to the online font precisely as soon as. Check out Zach’s explanation, beginning at 32:15, and the code snippet):

/* Load two internet fonts utilizing JavaScript */
/* Zach Leatherman: https://noti.st/zachleat/KNaZEg/the-five-whys-of-web-font-loading-performance#sWkN4u4 */

// Take away current @font-face blocks
// Create two
let font = new FontFace("Noto Serif", /* ... */);
let fontBold = new FontFace("Noto Serif, /* ... */);

// Load two fonts
let fonts = await Promise.all([
  font.load(),
  fontBold.load()
])

// Group repaints and render each fonts on the similar time!
fonts.forEach(font => paperwork.fonts.add(font));

To provoke a really early fetch of the fonts with Font Loading API in use, Adrian Bece suggests so as to add a non-breaking house nbsp; on the high of the physique, and conceal it visually with aria-visibility: hidden and a .hidden class:

<physique class="no-js">
  <!-- ... Web site content material ... -->
  <div aria-visibility="hidden" class="hidden" fashion="font-family: '[web-font-name]'">
      <!-- There's a non-breaking house right here -->
  </div>
  <script>
    doc.getElementsByTagName("physique")[0].classList.take away("no-js");
  </script>
</physique>

This goes together with CSS that has totally different font households declared for various states of loading, with the change triggered by Font Loading API as soon as the fonts have efficiently loaded:

physique:not(.wf-merriweather--loaded):not(.no-js) {
  font-family: [fallback-system-font];
  /* Fallback font types */
}

.wf-merriweather--loaded,
.no-js {
  font-family: "[web-font-name]";
  /* Webfont types */
}

/* Accessible hiding */
.hidden {
  place: absolute;
  overflow: hidden;
  clip: rect(0 0 0 0);
  peak: 1px;
  width: 1px;
  margin: -1px;
  padding: 0;
  border: 0;
}

Should you ever questioned why regardless of all of your optimizations, Lighthouse nonetheless suggests to eradicate render-blocking sources (fonts), in the identical article Adrian Bece supplies a number of techniques to make Lighthouse happy, together with a Gatsby Omni Font Loader, a performant asynchronous font loading and Flash Of Unstyled Textual content (FOUT) dealing with plugin for Gatsby.

Now, many people is perhaps utilizing a CDN or a third-party host to load internet fonts from. On the whole, it’s always higher to self-host all your static assets in case you can, so think about using google-webfonts-helper, a hassle-free method to self-host Google Fonts. And if it’s not potential, you possibly can maybe proxy the Google Font files through the page origin.

That is fairly necessary particularly as since Chrome v86 (launched October 2020), cross-site sources like fonts can’t be shared on the same CDN anymore — as a result of partitioned browser cache. This conduct was a default in Safari for years.

But when it’s not potential in any respect, there’s a method to get to the fastest possible Google Fonts with Harry Roberts’ snippet:

<!-- By Harry Roberts.
https://csswizardry.com/2020/05/the-fastest-google-fonts/

- 1. Preemptively heat up the fonts’ origin.
- 2. Provoke a high-priority, asynchronous fetch for the CSS file. Works in
-    most fashionable browsers.
- 3. Provoke a low-priority, asynchronous fetch that will get utilized to the web page
-    solely after it’s arrived. Works in all browsers with JavaScript enabled.
- 4. Within the unlikely occasion {that a} customer has deliberately disabled
-    JavaScript, fall again to the unique technique. The excellent news is that,
-    though it is a render-blocking request, it might nonetheless make use of the
-    preconnect which makes it marginally sooner than the default.
-->

<!-- [1] -->
<hyperlink rel="preconnect"
      href="https://fonts.gstatic.com"
      crossorigin />

<!-- [2] -->
<hyperlink rel="preload"
      as="fashion"
      href="$CSS&show=swap" />

<!-- [3] -->
<hyperlink rel="stylesheet"
      href="$CSS&show=swap"
      media="print" onload="this.media="all"" />

<!-- [4] -->
<noscript>
  <hyperlink rel="stylesheet"
        href="$CSS&show=swap" />
</noscript>

Harry’s technique is to pre-emptively heat up the fonts’ origin first. Then we provoke a high-priority, asynchronous fetch for the CSS file. Afterwards, we provoke a low-priority, asynchronous fetch that will get utilized to the web page solely after it’s arrived (with a print stylesheet trick). Lastly, if JavaScript isn’t supported, we fall again to the unique technique.

Ah, speaking about Google Fonts: you possibly can shave as much as 90% of the scale of Google Fonts requests by declaring only characters you need with &textual content. Plus, the support for font-display was added recently to Google Fonts as nicely, so we will use it out of the field.

A fast phrase of warning although. Should you use font-display: non-compulsory, it might be suboptimal to additionally use preload as it’ll set off that internet font request early (inflicting community congestion when you have different vital path sources that must be fetched). Use preconnect for sooner cross-origin font requests, however be cautious with preload as preloading fonts from a special origin wlll incur community competition. All of those methods are coated in Zach’s Web font loading recipes.

Alternatively, it is perhaps a good suggestion to opt out of web fonts (or no less than second stage render) if the person has enabled Reduce Motion in accessibility preferences or has opted in for Information Saver Mode (see Save-Data header), or when the person has a gradual connectivity (by way of Network Information API).

We will additionally use the prefers-reduced-data CSS media question to not outline font declarations if the person has opted into data-saving mode (there are other use-cases, too). The media question would mainly expose if the Save-Information request header from the Shopper Trace HTTP extension is on/off to permit for utilization with CSS. Presently supported only in Chrome and Edge behind a flag.

Metrics? To measure the online font loading efficiency, contemplate the All Text Visible metric (the second when all fonts have loaded and all content material is displayed in internet fonts), Time to Real Italics in addition to Web Font Reflow Count after first render. Clearly, the decrease each metrics are, the higher the efficiency is.

What about variable fonts, you may ask? It’s necessary to note that variable fonts may require a significant performance consideration. They offer us a wider design house for typographic decisions, nevertheless it comes at the price of a single serial request against numerous particular person file requests.

Whereas variable fonts drastically reduce the overall combined file size of font files, that single request is perhaps gradual, blocking the rendering of all content material on a web page. So subsetting and splitting the font into character units nonetheless matter. On the nice facet although, with a variable font in place, we’ll get precisely one reflow by default, so no JavaScript will probably be required to group repaints.

Now, what would make a bulletproof internet font loading technique then? Subset fonts and put together them for the 2-stage-render, declare them with a font-display descriptor, use Font Loading API to group repaints and retailer fonts in a persistent service employee’s cache. On the primary go to, inject the preloading of scripts simply earlier than the blocking exterior scripts. You may fall again to Bram Stein’s Font Face Observer if mandatory. And in case you’re excited about measuring the efficiency of font loading, Andreas Marschke explores performance tracking with Font API and UserTiming API.

Lastly, don’t overlook to incorporate unicode-range to interrupt down a big font into smaller language-specific fonts, and use Monica Dinculescu’s font-style-matcher to attenuate a jarring shift in structure, as a consequence of sizing discrepancies between the fallback and the online fonts.

Alternatively, to emulate an online font for a fallback font, we will use @font-face descriptors to override font metrics (demo, enabled in Chrome 87). (Notice that changes are difficult with difficult font stacks although.)

Does the longer term look vibrant? With progressive font enrichment, ultimately we would have the ability to “obtain solely the required a part of the font on any given web page, and for subsequent requests for that font to dynamically ‘patch’ the unique obtain with extra units of glyphs as required on successive web page views”, as Jason Pamental explains it. Incremental Transfer Demo is already accessible, and it’s work in progress.





Source link