如何使用Tailwind CSS预加载本地字体?能否通过tailwind.config.js配置?
使用Tailwind CSS预加载字体的方法
可以在tailwind.config.js中配置字体的别名和使用规则,但预加载字体本身需要通过HTML的预加载标签实现,Tailwind不直接负责资源预加载,不过两者可以配合完成“UI渲染前加载字体”的需求,具体步骤如下:
1. 在Tailwind配置文件中定义字体
首先在tailwind.config.js的theme.extend.fontFamily中配置你要使用的字体,示例:
/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./src/**/*.{html,js}"], theme: { extend: { fontFamily: { // 配置自定义字体别名 custom: ['CustomFont', 'serif'], // 也可以覆盖默认sans字体 sans: ['Inter', 'system-ui', 'sans-serif'], }, }, }, plugins: [], }
如果是本地字体(非系统字体或CDN字体),需要先在全局CSS文件(比如src/styles.css)中用@font-face声明字体:
@font-face { font-family: 'CustomFont'; src: url('../fonts/CustomFont-Regular.woff2') format('woff2'), url('../fonts/CustomFont-Regular.woff') format('woff'); font-weight: 400; font-style: normal; font-display: swap; /* 优化字体加载体验,避免无样式文本闪烁 */ } /* 如果有其他字重,比如粗体,也需要声明 */ @font-face { font-family: 'CustomFont'; src: url('../fonts/CustomFont-Bold.woff2') format('woff2'), url('../fonts/CustomFont-Bold.woff') format('woff'); font-weight: 700; font-style: normal; font-display: swap; }
2. 添加HTML预加载标签
要在UI渲染前完成字体加载,需要在HTML的<head>中添加<link rel="preload">标签,让浏览器优先加载字体资源:
<head> <!-- 预加载常规字重的CustomFont --> <link rel="preload" href="/fonts/CustomFont-Regular.woff2" as="font" type="font/woff2" crossorigin> <!-- 预加载粗体字重的CustomFont --> <link rel="preload" href="/fonts/CustomFont-Bold.woff2" as="font" type="font/woff2" crossorigin> <!-- 引入包含Tailwind和@font-face的全局CSS文件 --> <link rel="stylesheet" href="/src/styles.css"> </head>
rel="preload":告诉浏览器这是优先级很高的资源,需要提前加载as="font":指定资源类型为字体,浏览器会优化加载策略crossorigin:即使是本地字体,部分浏览器也需要这个属性才能正确预加载
3. 在页面中使用配置好的字体
通过Tailwind的字体类名直接使用即可,比如:
<h1 class="font-custom text-3xl">使用预加载字体的标题</h1> <p class="font-sans text-base">使用自定义sans字体的段落</p>
关键说明
tailwind.config.js的作用是定义字体的使用规则和别名,让你可以通过Tailwind类名快速引用字体,但它不处理资源加载逻辑- 预加载的核心是HTML的
preload标签,配合font-display: swap可以在字体加载完成前用系统字体占位,避免页面闪烁,同时确保字体加载完成后立即替换
内容的提问来源于stack exchange,提问作者amatinya
相关产品推荐
相关产品推荐

