如何异步导入本地字体?

发布于 2025-01-15 03:00:06 字数 1089 浏览 2 评论 0原文

我最近开始在本地托管我的网站使用的几种字体。在我这样做之前,我从谷歌字体异步加载它们以避免加载阻塞,但现在我不知道如何去做。

之前的 HTML 语法:

<link rel="import" href="//fonts.googleapis.com/css2?family=Titillium+Web:wght@300;400;600&display=swap" async>

之后的 CSS 语法:

@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-300.woff2") format('woff2');
    font-weight: lighter;
    font-style: normal;
    font-display: swap
}
@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-400.woff2") format('woff2');
    font-weight: normal;
    font-style: normal;
    font-display: swap
}
@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-600.woff2") format('woff2');
    font-weight: bold;
    font-style: normal;
    font-display: swap
}

仅使用交换仍然会导致阻塞(链接关键请求):

在此处输入图像描述

所以我需要像以前一样完全异步加载。我还没有找到在 CSS 中异步加载的方法,并且我不确定如何在使用 HTML 加载时正确定义字体。我能做些什么?

I have recently started hosting the few fonts I use for my website localy. Before I did that I was loading them from google fonts asyn to avoid loading blocking but now I'm not sure how to go about it.

Syntax in HTML before:

<link rel="import" href="//fonts.googleapis.com/css2?family=Titillium+Web:wght@300;400;600&display=swap" async>

Syntax in CSS after:

@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-300.woff2") format('woff2');
    font-weight: lighter;
    font-style: normal;
    font-display: swap
}
@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-400.woff2") format('woff2');
    font-weight: normal;
    font-style: normal;
    font-display: swap
}
@font-face {
    font-family: "Titillium Web";
    src: url("../fonts/titillium-web-600.woff2") format('woff2');
    font-weight: bold;
    font-style: normal;
    font-display: swap
}

Just using swap still causes blocking(chaining critical requests):

enter image description here

so I need to load fully async like before somehow. I haven't found a way to load async in CSS and I'm not sure how to properly define the fonts while using HTML loading. What can I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文