【问题标题】:How to preload custom fonts with webpack/rails 6如何使用 webpack/rails 6 预加载自定义字体
【发布时间】:2021-02-18 07:24:11
【问题描述】:

我想预加载自定义字体。我正在使用带有 webpack 的 rails 6。

在 config/_fonts.scss 中:

@font-face {
  font-family: 'customfont';
  src: font-url('customfont.eot?81236734');
  src: font-url('customfont.eot?81236734#iefix') format('embedded-opentype'),
       font-url('customfont.woff2?81236734') format('woff2'),
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

我在我的应用程序 scss 中导入此字体:

@import "config/index";

但我想预加载此字体。这样做的最佳做法是什么?

【问题讨论】:

    标签: css ruby-on-rails webpack fonts web-performance


    【解决方案1】:

    最近有同样的问题。这是我使用 webpack 为 Rails 6 所做的。 据我了解,webpack 会生成manifest.json,您可以在应用程序的公共目录中找到它(它在webpacker.yml 中配置)。

    当您打开 manifest.json 时,您还应该看到字体参考。 在我的清单中,它看起来类似于以下内容:

    "media/images/some-font.woff2": "/packs/media/images/4d419d560889218c146f.woff2"
    

    现在,当您知道打包路径可用时,很容易在 head 部分构建预加载(haml 中的示例):

    = preload_link_tag(asset_pack_path('media/images/some-font.woff2'))  
    

    【讨论】:

      【解决方案2】:

      如果我没记错的话,你必须按照这篇文章在视图的头部添加一个链接标签:https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

      然后对于 href 使用 asset_pack_url 帮助器以指向正确的文件。

      还要注意asset_path_url 需要指向您编译的资产所在的文件夹,而不要提及“public/packs”

      那么您可能必须使用 <%= asseet_pack_url 'media/fonts/my-font.woff' %> 之类的东西或类似的东西

      (我也在考虑你正在使用 Webpack 来传递图像/css 和字体。如果你使用 asdset 管道,只需使用通常的帮助器)

      【讨论】:

        猜你喜欢
        • 2019-12-26
        • 2016-10-29
        • 2019-02-27
        • 2019-10-31
        • 1970-01-01
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多