Correct way to load fonts in Vue.js

Correct way to load fonts in Vue.js

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

Declare fonts with font-face correctly

Ensuring that fonts are declared correctly 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 we get into this question, let's take a look at the structure of a 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 do this in main.css by declaring the font-face 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");
}

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

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

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

Another thing to note is the src order. First, we check if a local copy of the font is available ( local("Roboto") ) and use that. Many Android devices come with Roboto pre-installed, and in this case we will use the pre-installed copy. If there is no local copy, proceed with downloading the woff2 format if your browser supports it. Otherwise, it skips to the next font in the supported declaration.

Preload fonts

Once your custom font is declared, you can use <link rel="preload"> to tell the browser to preload the font ahead of time. 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 fetching the resource as soon as possible, and as="font" tells the browser that this is a font, so it prioritizes the request. Also note the crossorigin="anonymous" because without this attribute the preloaded fonts will be discarded by the browser. This is because the browser obtains the font anonymously, so using this attribute can make anonymous requests.

Using link=preload increases the chances that custom fonts will be downloaded before they are needed. This small tweak significantly speeds up font loading times, thereby speeding up text rendering in your web applications.

Use link=preconnect to host fonts

When using hosted fonts from sites like Google fonts, you can get faster load times by using link=preconnect. It tells the browser to establish a connection to the domain name in advance.

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"
/>

This will establish the initial connection to the origin https://fonts.gstatic.com, and when the browser needs to fetch a resource from the origin, the connection is already established. The difference between the two can be seen in the figure below.

When loading fonts without link=preconnect you can see the time it takes to connect (DNS lookup, initial connection, SSL, etc). When using link=preconnect like this, the results look very different.

Here you'll notice that the time taken for the DNS lookup, initial connection, and SSL is gone because the connection has already been made.

Using 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 longer max-age expires header for fonts so that browsers cache the fonts longer. If you’re building a progressive web app (PWA), you can use service workers to cache fonts and serve them directly from the cache.

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

vue create pwa-app

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

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

cd pwa-app
yarn serve

You will notice that there is a file registerServiceWorker in the src directory, which contains the default configuration. In the root directory of your project, create vue.config.js if it doesn't exist, and if it does, add the following content:

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

The vue-cli tool uses the PWA plugin to generate a service worker. Under the hood, it uses Workbox to configure the service worker and the elements it controls, the caching strategy to use, and other necessary configuration.

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

Next, we add our 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 finished developing your Vue application, you can build it by running the following command from your terminal:

yarn build

This will output the results into the dist folder. If you inspect the contents of the folder, you’ll notice a file that looks something like precache-manifest.1234567890.js. It contains the 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"
 },
 ...
]);

Everything in the public/ folder is cached by default, including custom fonts. With this in place, you can serve your application using packages like service, or host the dist folder on a web server to view the results. Below you can find a screenshot of the application.

On subsequent visits, the fonts are loaded from the cache, which speeds up application loading times.

in conclusion

In this post, we looked at some best practices to apply when loading fonts in your Vue applications. Using these practices will ensure that the fonts you provide look great without affecting your app's performance.

This is the end of this article about the correct way to load fonts in Vue.js. For more relevant vue.js font loading content, please search 123WORDPRESS.COM’s previous articles or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to font icon not displaying after Vue.js iview is packaged and launched
  • How to introduce font .ttf into vue project
  • How to introduce Font Awesome into Vue third-party font icons
  • Solve the problems of font icon error and non-display when introducing Vue project

<<:  Example of how to deploy a Django project using Docker

>>:  Summary of several MySQL installation methods and configuration issues

Recommend

A brief talk about the diff algorithm in Vue

Table of contents Overview Virtual Dom principle ...

Pure CSS header fixed implementation code

There are two main reasons why it is difficult to...

How to redirect nginx directory path

If you want the path following the domain name to...

How can MySQL effectively prevent database deletion and running away?

Table of contents Safe Mode Settings test 1. Upda...

How to set directory whitelist and IP whitelist in nginx

1. Set a directory whitelist: Do not set restrict...

js to achieve simple product screening function

This article example shares the specific code of ...

Docker data volume container creation and usage analysis

A data volume container is a container specifical...

MySQL Tutorial: Subquery Example Detailed Explanation

Table of contents 1. What is a subquery? 2. Where...

How to clear the timer elegantly in Vue

Table of contents Preface optimization Derivative...

KVM virtualization installation, deployment and management tutorial

Table of contents 1.kvm deployment 1.1 kvm instal...

Mini Program Recording Function Implementation

Preface In the process of developing a mini progr...

How to add Nginx to system services in CentOS7

Introduction After compiling, installing and solv...

Detailed steps for installing Harbor, a private Docker repository

The installation of Harbor is pretty simple, but ...