Home Web Front-end JS Tutorial How to Improve Page Performance with a Font Loader

How to Improve Page Performance with a Font Loader

Feb 21, 2025 am 08:25 AM

How to Improve Page Performance with a Font Loader

Summary of key points

  • Using a font loader can significantly improve web page performance because it can control the loading timing and way of web page fonts, thereby shortening page loading time and avoiding "unstyled text flickering" (FOUT).
  • webfontloader The JavaScript library is a very useful tool that can load fonts from various sources in the background after the page is loaded, and allows customization of the loading process using CSS and JavaScript callback functions.
  • The font usage and user experience must be balanced; while fonts can enhance the aesthetics of the website, loading a large number of fonts or fonts will slow down the page loading, especially on mobile devices. Therefore, using font loaders and implementing alternate fonts can help maintain a smooth and fast user experience.

Special thanks to Jason Pamental for the inspiration that led to the writing of this article. Otherwise I might never think about this! The last time you used Arial, Times New Roman, Helvetica or… (chilling) on ​​a webpage… When was Comic Sans? Web fonts appear too late, but once they appear, we never look back. Fonts are fun, (usually) free and easy to implement:

<code>@import url(http://fonts.googleapis.com/css?family=Ubuntu:300,300italic,400,400italic,500,500italic,700,700italic);</code>
Copy after login
Copy after login

You can then use the font in your page, for example:

<code>body {
    font-family: Ubunutu, sans-serif;
    font-weight: 400;
}</code>
Copy after login
Copy after login

Fonts work properly on mobile devices, so users get a good experience in your responsive web design. Or is it really the case?

After the picture, fonts are usually the largest resource in the webpage. The Ubuntu font above adds nearly 250KB to the page, which is evident on slower mobile network connections. Chrome, IE, Safari, and Opera leave blank space when the font is loaded, so the page cannot be used. Firefox and older versions of Opera display text in alternate fonts and switch—this is called unstyled text flashing (FOUT). Neither of these situations are ideal. We rarely worry about font weighting issues and make excuses like “This is just a problem with the first page” or “Many users have cached fonts.” We may omit fonts that are less used; for example, removing most Ubuntu italic styles can save nearly 40%. Few people dare to adopt obvious solutions using standard operating system fonts – our clients and designers will never forgive us.

JavaScript webfontloader

Luckily, there is another option: webfontloader. This JavaScript library can load fonts from Google, Typekit, Fonts.com, Fontdeck, or your own server in the background after the page loads. The library itself adds an additional 17KB to the page, but it will also be downloaded as a background process. To load the Ubuntu font set above, we create a global object called WebFontConfig that defines our fonts and settings, and then loads the webfontloader itself:

<code>@import url(http://fonts.googleapis.com/css?family=Ubuntu:300,300italic,400,400italic,500,500italic,700,700italic);</code>
Copy after login
Copy after login

Therefore, we can determine whether some or all of the fonts are loaded based on the device and bandwidth capacity. Ideally, we can use the Network Information API, but browser support is still limited. Alternatively, note the timeout setting in WebFontConfig; if the font file takes more than two seconds to download, the request will be abandoned.

CSS callback function

webfontloader applies the class name to the html element during operation:

  • .wf-loading — All fonts are requested
  • .wf-active — All fonts are available
  • .wf-inactive — Cannot load any fonts

Class name will also be applied to each font:

  • .wf-<familyname>-<fvd>-loading</fvd></familyname> — Single font requested
  • .wf-<familyname>-<fvd>-active</fvd></familyname> — Available in a single font
  • .wf-<familyname>-<fvd>-inactive</fvd></familyname> — Unable to load a single font

where <familyname></familyname> is a purified version of the font name, and <fvd></fvd> is a variant description, such as i4 represents italics of 400 thickness. This allows us to switch fonts after font downloads—the same way that Firefox does, for example:

<code>body {
    font-family: Ubunutu, sans-serif;
    font-weight: 400;
}</code>
Copy after login
Copy after login

JavaScript callback function

Similar JavaScript callback functions can be defined in WebFontConfig, although this is rarely useful, such as:

var WebFontConfig = {
    google: {
        families: [ 'Ubuntu:400,300,400italic,300italic,500italic,500,700,700italic:latin' ]
    },
    timeout: 2000
};

(function(){
    var wf = document.createElement("script");
    wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
        '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.async = 'true';
    document.head.appendChild(wf);
})();
Copy after login

Refer to the webfontloader documentation for more information.

Minimize FOUT

If your alternate font is very different from your web font in terms of style, thickness, or spacing, unstyled text flashing can be harsh. However, with just a little experiment, you can adjust the alternate font, thickness, line height and margins to ensure that the page elements remain roughly the same when loading the web fonts... See Craig Buckler on CodePen (@craigbuckler) Article "How to Use Font Loader".

Click the "Switch Font" button to view the font switching effect. This change is not entirely unobvious, but it is important that if users start reading, they don't lose their place. You can add a "Switch Font" button to any page to help you evaluate the appropriate alternate style:

/* 默认操作系统字体 */
body {
    font-family: arial, sans-serif;
}

/* 字体现在已加载 */
.wf-active body {
    font-family: 'Ubuntu';
}
Copy after login

In short: font usage may be free, but please try to minimize the cost of users. If you are loading 1MB of font files, your carefully created responsive web design is not suitable for mobile devices!

(The following is the FAQ part, which has been rewritten and integrated based on the original text, and some of the content has been streamlined)

Frequently Asked Questions about Using Font Loader to Improve Web Page Performance

What is a font loader? Why is it important for page performance?

Font Loader is a tool that allows you to control how web fonts are loaded on your website. It is important for page performance because it can help reduce the loading time of the website. When the web page is loading, the browser must download all necessary resources, including fonts. If the font is large or large, this will slow down the page loading time. Font loaders allow you to control how and how these fonts are loaded, which can significantly improve your page performance.

How does the font loader improve page performance?

Font loader improves page performance by allowing you to control the loading of web fonts. You can choose to load fonts asynchronously, which means they won't block rendering for the rest of the page. This can significantly reduce the time it takes for the page to become interactive. In addition, the font loader can help prevent the "unstyled text flickering" (FOUT) phenomenon, where the browser displays alternate fonts while the web font is still loading.

What are the commonly used font loaders?

Several commonly used font loaders are available, including Google's WebFont Loader and Typekit's WebFont Loader. Both tools provide multiple options to control how web fonts are loaded. There are also some WordPress plugins (such as Developry Google Fonts) that can easily implement font loading on your website.

How to implement font loader on my website?

Implementing a font loader on your website usually requires adding a script to your HTML. This script will load the font loader, and you can then use the font loader's API to control how web fonts are loaded. The exact process may vary depending on the font loader you are using, so it is better to refer to the documentation for specific instructions.

Can I use the font loader with any web font?

Most font loaders are compatible with any web font, as long as the font is hosted in a way that allows the font loader to load. This includes self-hosted fonts and fonts hosted by font services such as Google Fonts or Typekit.

Will using a font loader affect the appearance of my fonts?

Using a font loader may affect the appearance of your fonts as it can help prevent FOUT. However, it should not change the actual design or style of the font. If you notice any changes in the appearance of the font after implementing the font loader, it may be due to configuration issues.

What is "Unstyled text flashing" (FOUT)? How does a font loader prevent it?

FOUT is a phenomenon where the browser displays alternate fonts when the web font is still loading. This can cause brief text flickering, with the font different from the final font, which can make the user feel uncomfortable. Font loaders prevent FOUT by allowing you to control when you apply web fonts to text. For example, you can choose to hide text until the web font is loaded, or you can display the text in the alternate font and replace it after the web font is loaded.

Can font loader improve SEO of my website?

Yes, font loaders can improve your website's SEO by reducing page loading time. Page loading time is a factor that search engines consider when ranking websites, so you can do anything to reduce it, which may improve your SEO.

Are there any disadvantages of using a font loader?

One potential drawback of using a font loader is that it may increase the complexity of the website code. However, the benefits of improved page performance and user experience often outweigh this disadvantage. Additionally, many font loaders have good documentation and support, making them relatively easy to implement.

How to tell if the font loader is improving my page performance?

You can use various tools to measure your page performance before and after implementing the font loader. These tools can provide metrics such as page loading time, first draw time, and interactive time, which can help you quantify the impact of the font loader. Some commonly used performance measurement tools include Google's Lighthouse and WebPageTest.

The above is the detailed content of How to Improve Page Performance with a Font Loader. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles