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

How to delete all contents in a directory using Ansible

Students who use Ansible know that Ansible only s...

CSS code to achieve background gradient and automatic full screen

CSS issues about background gradient and automati...

Design Reference Beautiful and Original Blog Design

All blogs listed below are original and uniquely ...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

Troubleshooting and solutions for MySQL auto-increment ID oversize problem

introduction Xiao A was writing code, and DBA Xia...

Analysis of the difference between emits and attrs in Vue3

Table of contents in conclusion Practice Analysis...

Getting Started Tutorial on Animating SVG Path Strokes Using CSS3

Without relying on JavaScript, pure CSS is used t...

JavaScript to implement random roll call web page

JavaScript writes a random roll call webpage for ...

Implement a simple data response system

Table of contents 1. Dep 2. Understand obverser 3...

Detailed explanation of CSS weight value (cascading) examples

•There are many selectors in CSS. What will happe...

Multiple methods to modify MySQL root password (recommended)

Method 1: Use the SET PASSWORD command MySQL -u r...

Vue implements tab navigation bar and supports left and right sliding function

This article mainly introduces: using Vue to impl...