【问题标题】:Flash of unstyled content when fading in text文本淡入时无样式内容的闪烁
【发布时间】:2019-10-15 00:18:36
【问题描述】:

当淡入应该使用 Google Fonts 字体设置样式的文本时,我想不出一种方法来防止出现未设置样式的内容。

看起来 fonts.googleapis.com 会在页面加载时加载,但直到文本应该淡入时才会加载 fonts.gstatic.com,这会导致文本出现短暂且难看的闪烁Times New Roman 或任何默认字体,然后才突然正确设置样式。

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Quicksand&display=swap" rel="stylesheet">

    <!-- Static CSS -->
    <link rel='stylesheet' type='text/css' href="main.css"/>
</head>

<body>
    <div>
        <button id="startButton">Start</button>
    </div>

    <div id="textDiv">
        <p id="textContents"></p>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>

    <!-- Static JavaScript -->
    <script src="main.js"></script>
</body>

CSS

#textDiv {
    font-size: 40px;
    font-family: 'Quicksand';
}

Javascript

var textDiv = $('#textDiv');
var text = $('#textContents');
var button = $('#startButton');

// handle click and add text
button.bind("click", function() {
    textDiv.hide();
    text.html("<p>Hello</p>");
    textDiv.fadeIn();
})

https://jsfiddle.net/eshapiro42/xmf23uqw/15/

任何帮助弄清楚如何防止这种情况将不胜感激!

【问题讨论】:

  • 请问您使用的是哪种浏览器?
  • 我使用的是 Google Chrome 版本 77.0.3865.90。

标签: javascript jquery html css fadein


【解决方案1】:

当您引用实际字体时,您可以preload 字体。您在此处引用的是一个样式表,该样式表将 @font-face 添加到您的文档中,并具有不同的 Quicksand 变体。

解决方案是将样式表链接粘贴到浏览器中并获取字体的直接链接,然后将其作为参考加载到 html 文档中:

<link rel="preload" href="ttps://fonts.gstatic.com/s/quicksand/v15/6xK-dSZaM9iE8KbpRA_LJ3z8mH9BOJvgkP8o58a-xDwxUD2GFw.woff" as="font" crossorigin>

【讨论】:

    【解决方案2】:

    在引用来自 Google 的字体时使用 display=block 请求参数。您的示例的完整 URL:

    https://fonts.googleapis.com/css?family=Quicksand&display=block

    这反过来会导致 Google 样式表在其 @font-face 声明中使用 font-display: block 规则。此规则将指定您宁愿文本在加载字体之前保持未呈现,而不是以本地字体呈现文本并在 webfont 准备好时重新呈现。

    来源:

    https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/webfont-optimization#customize_the_text_rendering_delay https://css-tricks.com/google-fonts-and-font-display/

    【讨论】:

      【解决方案3】:

      在 CSS 中,您可以添加 display: none; 并在您的 JavaScript 中添加

      $(function() {
        $('#textDiv').css('display', 'block');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-14
        • 2011-01-13
        • 2012-07-23
        • 2015-06-07
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多