使用@font-face和url()定义字体路径,通过JavaScript或Font Loading API实现动态加载,结合font-display控制显示行为,预加载与子集化优化性能,并配置CORS解决跨域问题。

在CSS中,
url()
url()
解决方案
使用@font-face
@font-face
url()
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/my-custom-font.woff2') format('woff2'),
url('path/to/my-custom-font.woff') format('woff');
font-weight: normal;
font-style: normal;
}按需应用字体: 关键在于不在页面初始加载时立即使用该字体。可以先使用系统默认字体,然后通过JavaScript事件(例如,用户交互、页面滚动到特定位置)或者CSS媒体查询,动态地将
font-family
立即学习“前端免费学习笔记(深入)”;
/* 初始样式,使用系统字体 */
body {
font-family: sans-serif;
}
/* 动态加载字体后的样式 */
body.custom-font-loaded {
font-family: 'MyCustomFont', sans-serif; /* 'MyCustomFont' 是我们定义的字体 */
}// JavaScript 示例 (使用classList添加类)
window.addEventListener('load', function() {
// 模拟字体加载完成 (实际情况需要监听字体加载事件,见下文)
setTimeout(function() {
document.body.classList.add('custom-font-loaded');
}, 1000); // 延迟1秒,模拟字体加载时间
});使用Font Loading API: 现代浏览器提供了Font Loading API,可以更精确地控制字体的加载。可以监听字体加载状态,并在字体加载完成后执行相应的操作。
// 检查字体是否已经加载
document.fonts.load('1em MyCustomFont').then(function() {
// 字体加载完成
document.body.classList.add('custom-font-loaded');
});预加载字体(Preload): 如果确定某个字体稍后一定会用到,可以使用
<link rel="preload">
<link rel="preload" href="path/to/my-custom-font.woff2" as="font" type="font/woff2" crossorigin>
注意:
crossorigin
如何避免字体闪烁(FOIT/FOUT)?
字体闪烁(Flash of Invisible Text/Flash of Unstyled Text)是指在自定义字体加载完成之前,浏览器先显示系统默认字体,然后切换到自定义字体时出现的视觉跳跃。解决这个问题的方法:
使用font-display
font-display
swap
fallback
optional
fallback
block
auto
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/my-custom-font.woff2') format('woff2'),
url('path/to/my-custom-font.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap; /* 或者使用其他值,根据需求选择 */
}结合Font Loading API和font-display
font-display: optional
如何优化字体文件大小?
字体文件的大小直接影响页面加载速度。优化字体文件大小的方法:
如何处理跨域字体加载问题?
如果字体文件托管在不同的域名下,可能会遇到跨域问题。解决跨域问题的方法:
设置CORS头部: 在托管字体文件的服务器上,设置
Access-Control-Allow-Origin
Access-Control-Allow-Origin: * // 允许所有域名访问 Access-Control-Allow-Origin: https://your-domain.com // 只允许特定域名访问
使用crossorigin
<link rel="preload">
crossorigin
<link rel="preload" href="path/to/my-custom-font.woff2" as="font" type="font/woff2" crossorigin>
如果字体文件不需要凭据(例如cookie),可以使用
crossorigin
Access-Control-Allow-Credentials
以上就是如何通过CSS的url()函数动态加载字体资源?url()优化字体样式管理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号