如何异步加载材质 UI 字体?



我使用Material-UI及其字体阻止第一页的渲染。默认情况下,如果我不加载任何字体,materialui 使用 Helvetica 字体。主要思想是使用它,直到下载 Roboto。

/signup (localhost)
…media/roboto-latin-500.4b218fc7.woff2 (localhost) - 763,7ms, 14,5KB
…media/roboto-latin-400.a2647ffe.woff2 (localhost) - 769,5ms, 14,5KB

如何异步导入字体而不是

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

import 'typeface-roboto'

我尝试实现一种具有"media"属性和@font面观察器的方法

<link rel="stylesheet" href="fonts.css" media="bogus"/>

但它不起作用。我还使用了 fontfaceobserver.com 的插件字体加载器

我使用Material-UI的1.0.0-beta.3版本。

webfontloader 库可用于推迟应用程序的启动,直到下载字体。 这是有益的,因为它允许您避免FOUT(无样式文本的闪光(,这是由于在下载预期的Web字体时使用默认字体呈现页面引起的

下面是使用 webfontloader 推迟应用程序启动的示例:

import React from 'react';
import { render } from 'react-dom';
import WebFont from 'webfontloader';
// callback that mounts the application
const app = () => {
render(
<div>Instead of this div, render your initial component/routes here</div>,
document.querySelector('#main'),
);
};
// postpone initiation of app until fonts are active
const webFontConfig = {
google: {
families: ['Roboto'],
},
custom: {
families: ['FontAwesome'],
urls: [
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
'https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css',
],
},
classes: false,
timeout: 1000,
active: app, // invoked when fonts are active
};
// application entry point
WebFont.load(webFontConfig);

在 Web 字体配置中,活动属性设置为一个函数,当字体已下载并可供使用时,将调用该函数。 请注意,在初次使用应用程序时,这可能看起来很慢,但借助缓存的好处,后续访问应该会快得多。

为了以正确的方式异步加载<link/>(没有太多的黑客攻击(,我建议阅读以下内容:https://codepen.io/tigt/post/async-css-without-javascript

它提供了一个非阻塞link加载解决方案,就像(当然,存在if IE条件,因为浏览器的工作方式可能不同(:

<head>
<!--[if IE]>
<link rel="stylesheet" href="style.css"> 
<![endif]-->
</head>
<body>
<!--[if !IE]> -->
<link rel="stylesheet" href="style.css" lazyload>
<!-- <![endif]-->
</body>

最新更新