Header Ads

Optimize Your Web Fonts

Optimize Your Web Fonts

According to httparchive.org, the mass of the fonts files weighs on average 100 KB in a web page, or more than the weight of the HTML and CSS files, and as much as a good big picture.
Another reading interesting: today more than 69% of web sites offer to download a custom font. It is far the ancient Arial, Verdana and Times New Roman from the good old days!
The problem is that according to the browsers a font file not loaded can block or alter the display of the content, which is especially observable on mobile devices.

A resource block?

The process of displaying a web page in the browser is such that the page remains white until all resources HTML, CSS (possibly JavaScript) are not loaded and that the document tree is not fully constituted. We talk of "blocking" resources.
We know that other types of resources such as images or videos are loaded asynchronously - the browser loads gradually - and have little impact on the speed.
What about files of fonts?
ressources bloquantes
The answer is "it depends of what we call blocking".

CARE and expanding in the place!

When a custom font is requested by the browser, several scenarios may occur until it is fully charged. The possible sequences include both "Doing" and "Expanding".

Throw him

The term "Care" means Flash Of Unstyled Text, approximate translation would be 'flash of unstyled text':
  • the browser makes a request of custom font file (Open without in the illustration below)
  • until the file is loaded, the alternative police is immediately displayed (here Arial)
  • When the police Open without being recovered, she replaces Arial
Flash Of Unstyled Text

The Endpoints

The term "Episode" means Flash Of Invisible Text (referred to as "invisible text" flash):
  • the browser makes a request of custom font file (here Open without ))
  • until the file is loaded, the content remains invisible (only appear some artifices such as the underlines from links for example)
  • When the police Open without being recovered, she appears in place of the invisible space.
Flash Of Invisible Text

What browsers do

At first glance, the behavior of care seems the most coherent and least unsettling: who could wish content to be invisible as long as the police are not responsible?
Would you believe that things are not as simple as they seem. For example: display icons (icons are) policies from pictograms, including the most famous is Awesome Font (used by Bootstrap):
fout icons
FOUT sur Alsacreations
To try to manage these disparities between the types of fonts and their uses, each browser has adopted his own behavior:
  • Internet Explorer immediately displays the alternative system font, then police custom as soon as it is loaded. It is a typical example of the care, practical for content but not ideal for fonts of icons,
  • Safari and the native Android browser show no content so that the custom font is not loaded. They chose the Endpoints
  • Chrome, Firefox and Opera have adopted an intermediate approach: they display no maximum content for 3 seconds, and then if the police are still not charged fold on the alternative, and finally the custom font will be displayed. It is a mix between Endpoints and doesn't care.
And specifications in all this? Well, they do not get wet too. Their recommendation is very officially: "user agents decide their strategy of loading fonts (hell or Endpoints) as long as the file is not loaded".
Based on this observation, are trying to establish strategies to limit the damage.

Optimize your files

Choose the right format

No suspense, forget your old FTT and EOT: the best in terms of price-quality font format is WOFF2 (Web Open Font Format 2) compatible with a majority of browsers and mobile office today.
However, plan an alternative format for the glorious old ones. The best choice is the iteration previous .woff recognized by more than 95% of the terminals.
As a guide, here is a comparison of the weight of the different formats of the police freeware Rocket Fuel :
  • rocketfuel.OTF: 104 KB
  • rocketfuel.ttf: 81 KB
  • rocketfuel.woff: 55 KB
  • rocketfuel.woff2: 43 KB
Your ideal @font-face statement can be summed up like this:
@font-face {
  font-family: kiwi;
  src:
    url("kiwi.woff2") format("woff2"),
    url("kiwi.woff") format("woff");
}
She will then apply the font to your items with a specific class:
.kiwi {
  font-family: kiwi, sans-serif;
}
Easy no?

Host thawing

Contrary to common belief, it is not always ideal to benefit from providers such as Google Fonts and Typekit fonts. These third parties ("third parties") that host the files can cause a dependency and delays as well as to other discomforts inherent in all these types of external services.
Host its melt on its own servers allows you full control of the files, their availability and their optimization. FYI, Alsacréations share a project Github "Webfonts" where it is possible to retrieve and host dozens of families of fonts optimized for the Web.

Go further with FontSquirrel

FontSquirrel Webfont Generator is a well-known free online tool for system integrators who wish to make the most of their web fonts.
FontSquirrel
After loading your font files, and in having enabled the Expert mode with all his superpowers, you can strive for perfection in terms of weight of final file without affecting the quality of your policy.
Among the interesting options, hold mainly:
  • subsetting: delete the unwanted character ranges, for example Cyrillic, Hebrew, or the Malaysian if they are not used in your site. You are will save a lot of space.
  • x-height matching: Allows you to resize the police referring to an alternative system font (Arial, Times, Georgia, etc.). This feature is a real pleasure in hell because it avoids too important differences in size, and therefore the offsets or line breaks, at the time of the flash between the alternative fonts and the final police
When you have finished your settings, FontSquirrel you will offer to download a complete file containing your different font files, but also a HTML page of demonstration matches its stylesheet CSS and code @font-face that it you enough to adapt to your project.

Loading strategies

Now that our police files are optimized in a perfect format, let's look at the behaviors of hell and is mentioned in the beginning of the article.
Whatever happens, we will suffer, so are trying to accommodate us at best!
I offer three different strategies, which can be combined:
  • load its files asynchronously
  • load them as soon as possible
  • load them conditionally

Load the file asynchronously

Load the files of police via JavaScript is a way of forcing throw him to ban the Endpoints that can be considered rightly as being "the worst behavior".
The idea is to make the browser that only alternative police should be displayed, then in a second time to load and display the font personalized via JavaScript. Therefore, the contents will be never invisible to the loading.
This technique requires to convert the melting base64 file to use it via Data-URI and store it in a CSS file. Then it's JavaScript which is commissioned to load our file of "font-CSS" in an asynchronous way.
Summary example of CSS file :
@font-face {
  font-family: kiwi;
  src:
    url(data:application/font-woff;
    charset=utf-8;base64,d09GRgABAAAAANnkABMAAAABPxgAAQA…)
    format("woff");
}
Summary example of JavaScript script :
<script>
// Déclaration de loadCSS ici...
function loadCSS() { ... }
// Chargement du fichier CSS
loadCSS("data-uri.css");
</script>

<noscript><link href="data-uri.css" rel="stylesheet"></noscript>

Charge as soon as possible

If you don't want to use JavaScript to improve the display of your web fonts, another strategy is possible: to speed up the loading of font files.
Note that W3C has recently proposed specification rel="preload" whose profits are perfectly explained in this excerpt from the excellent Mozilla's Documentation :
The value of the preload of the attribute rel for the < link > element to write declarative queries of recovery within the < head >element. You can indicate the resources page will need shortly after loading. This allows to preload them at the beginning of the loading of the page until the rendering step. So this ensures that the necessary resources are available earlier, thus avoiding to block the initial rendering of the page and improving performance.
The attribute rel=preload is unfortunately not recognized by all browsers currently, but there is a special bonus for good students such as Chrome or Firefox, and very soon their successors. Why not to start today your visitors to this very simple to implement bonus?

Shopify et rel preload
Here is an example illustrating how to preload in advance two font files:
<link rel="preload" href="fonte-1.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="fonte-2.woff2" as="font" type="font/woff2" crossorigin>

Load conditionally

Another strategy is to conditionally load the font files, or more accurately not to solicit them on a mobile device e.g. for performance reasons.
The goal is to propose a system font by default and to link the police customized using CSS Media Queries based on a screen size for example.
In practice, it is very simple to implement. For starters, be aware that the @font-face declaration does not impose the resource loading, it will be loaded until it is explicitly requested by applying it on a page element.
In practice, simply in order to not load and display "kiwi" melting when the screen is higher than 576px:
body {
  font-family: arial,sans-serif;
}
@media (min-width: 576px) {
  body {
    font-family: kiwi, arial, sans-serif;
  }
}
This method is very beneficial in terms of performance but is of course not ideal because:
  • accept that the police are different between the mobile version and the version of office
  • assume that a mobile is defined by its screen size, which is necessarily approximate
In this regard, be aware that more and more web sites (Booking, Medium, WordPress, GitHub, Alsacréations, among others) have stopped trying to impose a policy identical to all their visitors, even when it comes to a classic police: instead of offering Arial, Verdana or Times, they opted for a variable policy tailored to each operating system:
body {
  font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
}
This family of typefaces, called "System Font Stack" offers each user his usual font on its OS: on Windows it will be "Segoe UI" or "Tahoma" for older ones, on Android "Roboto", etc. So your visitors won't be surprised by your typographic choices and feel at home in your content pages.

No longer undergo throw him / episode?

In the more or less near future, ways can no longer suffer the undesirable behaviors of doing and expanding when the fonts are in transit to our browsers.
An official specification, Font Loading API, is expected in stores, and a FontFaceObserver emulator is already usable in production.

Make Loading API

The CSS Font Loading Module Level 3 specification is still in draft form but is nonetheless supported by a very large part of the recent browsers.
This module provides an interface script to manage the steps to load the files of police very finely and the behavior was adopted for the browser on a case by case basis.
var f = new FontFace("newfont", "url(newfont.woff)", {});
f.load().then(function (loadedFace) {
  document.fonts.add(loadedFace);
  document.body.style.fontFamily = "newfont, serif";
});
document.fonts.ready().then(function() {
  // Toutes les familles @font-face sont prêtes
});

FontFaceObserver

FontFaceObserver is a script of "polyfill" directed by Bram Stein to emulate Font Loading API for browsers that do not yet recognize the specification. Its implementation is quite simple.
JavaScript part:
// include fontFaceObserver here...
new w.FontFaceObserver( "Source Sans Pro" )
.check()
.then( function(){
  w.document.documentElement.className += " fonts-loaded";
});
CSS part:
body {
  font-family: sans-serif;
}
.fonts-loaded body {
  font-family: "Source Sans Pro", sans-serif;
}
This allows asynchronous loading of the file, and then once it is ready to be used, adding a class to the element root < html > to apply the font on the entire document properties.

Bonus: do-display

You know the font-display CSS property? Don't worry, you're not alone. Indeed, this novelty is the status of unofficial proposal, that is to say that she has not yet reached the stage of draft to W3C.
Is that this property has the good sense to realize exactly our fantasy, IE to be able to decide what will be the behavior of browsers during the loading of our fonts.
For example, it is possible to impose one's IE to display immediately the alternative font with the swap value :
@font-face {
  font-family: kiwi;
  src: ...;
  font-display: swap;
}
The support of browsers, not surprisingly, is almost zero today: Chrome has just implement it and it is likely that others will follow. In any case, you can add it as a bonus, you don't break the Web. 
You will find more information about this feature on the site of Zach Leatherman.

Bonus: variable fonts

Another area to monitor closely (thanks to ThomasLinard for his wise comment): that of the "Variable Fonts".
variable font
Without going into the details, let's say the variable fonts made their entry in CSS Fonts Module Level 4 and consist of a casting format that integrates in a single file all fats and other variations of families of police. Thus, rather than having to load a file for the classic version, another for the fat version, another for italics, etc all will be gathered into a single file. It is of course a blessing for web performance.

Conclusion

In the area of performance as well as aesthetics and ergonomics, the choice of your web fonts is of crucial importance. Their number and their weight will depend on the speed of your content and the quality of experience for your users.
Do not like the site of vanityfair.fr that mattered nearly 450 k of files of fonts at a time. Don't give in to the temptation to impose multiple loads just because "these 8 fonts are so classes". Make choices. Optimize. Opt for loading strategies. All of your visitors, without exception, will thank you.

No comments

Powered by Blogger.