Blog: blogging. Zhangbing. Site / 2021/04/07 /…

Adding fonts should not negatively impact performance. In this article, we’ll explore best practices for loading fonts in Vue applications.

The correct statementfont-faceThe font

Ensuring that fonts are properly declared is an important aspect of loading fonts. This is done by declaring the font of your choice using the Font-face property. In your Vue project, this declaration can be done in your root CSS file. Before getting into that, let’s look at the structure of the Vue application.

/root
  public/
    fonts/
      Roboto/
        Roboto-Regular.woff2
        Roboto-Regular.woff
    index.html
  src/
    assets/
      main.css
    components/
    router/
    store/
    views/
    main.js
Copy the code

We can declare font-face in main.css like this:

// src/assets/main.css

@font-face {
  font-family: "Roboto";
  font-weight: 400;
  font-style: normal;
  font-display: auto;
  unicode-range: U+000-5FF;
  src: local("Roboto"), url("/fonts/Roboto/Roboto-Regular.woff2") format("woff2"), url("/fonts/Roboto/Roboto-Regular.woff") format("woff");
}
Copy the code

The first thing to notice is font-display:auto. Using auto as a value enables the browser to display the font using the most appropriate strategy. This depends on factors such as network speed, device type, idle time, etc.

To have more control over how fonts are loaded, you should use font-display: block, which instructs the browser to briefly hide text until the font is fully loaded. Other possible values are swap, fallback, and optional. You can read more about them here.

Note unicode-range: U+ 000-5ff, which instructs the browser to load only the desired glyphs range (U+ 000-u +5FF). You also want to use the Woff and Woff2 font formats, which are optimized for use in most modern browsers.

Another thing to note is the SRC order. First, we check that a local copy of the font is available (local(“Roboto “)) and use it. Many Android devices have Roboto pre-installed, and in this case, we’ll use a pre-installed copy. If there is no local copy, continue downloading the Woff2 format with browser support. Otherwise, it jumps to the next font in the supported declaration.

Preloaded font

Once your custom font is declared, you can use to tell the browser to pre-load the font. In public/index.html, add the following:

<link rel="preload" as="font" href="./fonts/Roboto/Roboto-Regular.woff2" type="font/woff2" crossorigin="anonymous">
Copy the code

Rel = “preload” instructs the browser to start retrieving the resource as soon as possible, and as = “font” tells the browser that this is a font and therefore it prioritizes processing requests. Also note that crossorigin= “anonymous”, because without this attribute, preloaded fonts will be discarded by the browser. This is because the browser gets the font anonymously, so you can request it anonymously using this property.

Using link=preload increases the chance that custom fonts will be downloaded before they are needed. This small adjustment greatly speeds up the loading time of fonts, thus speeding up text rendering in your Web applications.

Host fonts using Link = preconnect

When using hosted fonts from sites like Google Fonts, you can get faster load times by using link=preconnect. It tells the browser to make a connection to the domain name ahead of time.

If you are using the Roboto font provided by Google Fonts, you can do the following in public/index.html:

<link rel="preconnect" href="https://fonts.gstatic.com">.<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
Copy the code

This establishes an initial connection to the origin fonts.gstatic.com, and the connection is established when the browser needs to fetch resources from the origin. You can see the difference between the two in the figure below.

When the font is loaded without link=preconnect, you can see how long the connection takes (DNS lookup, initial connection, SSL, etc.). When using link=preconnect like this, the results look very different.

Here, you’ll notice that the time spent on DNS lookup, initial connection, and SSL is gone because the connection has already been made.

Use service Workers to cache fonts

Fonts are static resources that don’t change much, so they are good candidates for caching. Ideally, your Web server should set a long Max-Age Expires header for the font so that the browser caches the font for longer. If you are building a progressive Web application (PWA), you can use Service Workers to cache fonts and serve them directly from the cache.

To start building PWA using Vue, use the VUe-CLI tool to generate a new project:

vue create pwa-app
Copy the code

Select Manually Select Features and then Progressive Web App (PWA) Support:

These are the only things we need to generate the PWA template. Once done, you can change the directory to PWA-app and then serve the app.

cd pwa-app
yarn serve
Copy the code

You will notice that there is a file registerServiceWorker in the SRC directory that contains the default configuration. In the root directory of the project, if vue.config.js does not exist, create it, if it does, add the following:

// vue.config.js
module.exports = {
  pwa: {
    workboxOptions: {
      skipWaiting: true.clientsClaim: true,}}}Copy the code

Vue-cli tool generates service workers using the PWA Plugin. At the bottom, it uses the Workbox to configure the service worker and the elements it controls, the caching policies to use, and other necessary configurations.

In the code snippet above, we make sure that our application is always controlled by the latest version of the service worker. This is necessary because it ensures that our users always check the latest version of the application. You can check out the Workbox configuration document to gain more control over the generated service worker behavior.

Next, we add the custom font to the public directory. I have the following structure:

root/
  public/
    index.html
    fonts/
      Roboto/
        Roboto-Regular.woff
        Roboto-Regular.woff2
Copy the code

Once the Vue application is developed, it can be built by running the following command from the terminal:

yarn build
Copy the code

This outputs the results to the dist folder. If you examine the contents of the folder, you will notice a file similar to precach-manifest.1234567890.js. It contains a list of assets to cache, which is just a list of key-value pairs containing revisions and urls.

self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "3628b4ee5b153071e725"."url": "/fonts/Roboto/Roboto-Regular.woff2"
  },
  ...
]);
Copy the code

Everything in the public/ folder is cached by default, including custom fonts. With this place, you can serve your application with a package like Service, or host the Dist folder on a Web server to view the results. You can find a screenshot of the app below.

On subsequent access, the font is loaded from the cache, which speeds up the application’s load time.

conclusion

In this article, we looked at some of the best practices applied when loading fonts in Vue applications. Using these practices will ensure that the fonts you provide look good without affecting the performance of your application.