头图

Best practices for loading fonts in Vue.js

杜尼卜
中文
Original blog: https://blog.zhangbing.site/2021/04/07/best-practices-for-loading-fonts-in-vue/

Adding fonts should not have a negative impact on performance. In this article, we will explore the best practices for loading fonts in Vue applications.

Correctly declare the font of font-face

Ensuring the correct declaration of fonts is an important aspect of loading fonts. This is achieved by using the font-face attribute to declare the font of your choice. In your Vue project, this declaration can be done in your root CSS file. Before entering this question, let's take a 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

We can make the font-face statement main.css

// 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");
}

The first thing to note is font-display:auto . Using auto as the value allows the browser to use the most appropriate strategy to display the font. It depends on factors such as network speed, device type, idle time, etc.

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

Note that unicode-range: U+000-5FF , which instructs the browser to load only the required glyph range (U+000-U+5FF). You also want to use the woff and woff2 font formats, which are optimized formats that can be used in most modern browsers.

src to note is the sequence of 06076b62322f44. First, we check if a local copy of the font is available ( local("Roboto”) ) and use it. Many Android devices have Roboto pre-installed, in this case we will use the pre-installed copy. If there is no local copy, continue to download the woff2 format if supported by the browser. Otherwise, it will skip to the next font in the supported statement.

Preload fonts

Once your custom font is declared, you can use <link rel="preload"> tell the browser to preload the font in advance. In public/index.html , add the following:

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

rel = “preload” instructs the browser to start acquiring resources as soon as possible, and as = “font” tells the browser that this is a font, so it processes requests first. Also pay attention to crossorigin=“anonymous" , because without this attribute, preloaded fonts will be discarded by the browser. This is because the browser obtains the font anonymously, so you can request it anonymously by using this attribute.

Using link=preload can increase the chance of custom fonts being downloaded before they are needed. This small adjustment greatly speeds up font loading time, which in turn speeds up text rendering in your web application.

Use link=preconnect to host fonts

When using Google fonts and other website hosting fonts, you can get faster loading time link=preconnect It tells the browser to establish a connection with the domain name in advance.

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

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

In this way, https://fonts.gstatic.com can be established. When the browser needs to obtain resources from the origin, the connection has been established. The difference between the two can be seen from the figure below.

link=preconnect is not used when loading fonts, you can see the time required to connect (DNS lookup, initial connection, SSL, etc.). When using link=preconnect like this, the result looks very different.

Here, you will find that the time taken for DNS lookup, initial connection, and SSL no longer exists, because the connection has already been made before.

Use service workers to cache fonts

Fonts are static resources and do not change much, so they are good candidates for caching. Ideally, your web server should set a longer max-age expires for the font, so that the browser will cache the font longer. If you are building a progressive web application (PWA), then you can use service workers to cache fonts and serve them directly from the cache.

To start building a PWA with Vue, use the vue-cli tool to generate a new project:

vue create pwa-app

Select Manually select features option, and then select Progressive Web App (PWA) Support :

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

cd pwa-app
yarn serve

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

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

The vue-cli tool uses PWA plugin generate service workers. At the bottom, it uses Workbox to configure the service worker and the elements it controls, the caching strategy to be used, and other necessary configurations.

In the above code snippet, we want to ensure 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 behavior of the generated service worker.

Next, we will 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

Once you have completed the development of the Vue application, you can build it by running the following commands from the terminal:

yarn build

This will output the results to the dist folder. If you check the contents of the folder, you will notice a file precache-manifest.1234567890.js It contains a list of assets to be cached, 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"
  },
  ...
]);

public/ folder is cached by default, including custom fonts. With this place, you can use a package like service to serve your application, or dist folder on a web server to view the results. You can find a screenshot of the app below.

In subsequent visits, the font is loaded from the cache, which can speed up the loading time of the application.

in conclusion

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

阅读 725

前端全栈开发者
专栏首发于公众号《前端全栈开发者》,订阅关注第一时间阅读好文
avatar
杜尼卜
前端工程师

做工程师不做码农、全栈开发工程师、持续学习者

11k 声望
5.6k 粉丝
0 条评论
你知道吗?

avatar
杜尼卜
前端工程师

做工程师不做码农、全栈开发工程师、持续学习者

11k 声望
5.6k 粉丝
宣传栏