【问题标题】:How to async load Material ui fonts?如何异步加载 Material ui 字体?
【发布时间】:2018-01-10 21:28:16
【问题描述】:

我使用 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-face观察者实现一个方法

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

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

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

【问题讨论】:

    标签: css reactjs fonts material-ui


    【解决方案1】:

    webfontloader 库可用于推迟应用程序的启动,直到字体下载完成。这是有益的,因为它允许您avoid FOUT (Flash of Unstyled Text),这是由于在下载预期的网络字体时使用默认字体渲染页面而引起的

    这是一个使用 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);
    

    在网络字体配置中,active 属性设置为一个函数,当字体下载并准备好使用时将调用该函数。请注意,这在您的应用程序的初始使用中可能看起来很慢,但借助缓存的优势,后续访问应该会快得多。

    【讨论】:

    • 感谢您的回答。我需要更快地获得第一个有意义的油漆。与你的建议相反。如果您仔细阅读了文本,您应该明白在下载预期的网络字体时使用默认字体呈现页面正是我所需要的。但我会尝试任何方式。
    • 这很好,但要准备好在渲染时执行测量的组件出现闪烁或其他问题。它们将使用默认字体进行测量,Roboto 将完成加载,并且由于字体大小的不同,测量结果将不正确(请参阅:选定选项卡的墨条)。
    • 如果我在 HTML 中使用 async 属性导入 webfontloader 就可以了
    【解决方案2】:

    为了以正确的方式加载&lt;link/&gt; async(没有太多的黑客攻击),我建议阅读: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>
    

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 2019-09-05
      • 2021-01-20
      • 1970-01-01
      相关资源
      最近更新 更多