最近工作中,遇到一个页面。需要使用设计提供字体,但因字体过大导致页面加载速度很慢。梳理了一下解决方案
解决方案如下
const url = `https://image-1252680882.cos.ap-shanghai.myqcloud.com/act/2020/HYRunYuan-75W.ttf`;
// do something...
const link = document.createElement("style");
link.rel = "preload";
link.textContent = `@font-face {
font-family: HYRunYuan;
font-weight: 400;
font-style: normal;
src: url("${url}");
}`;
document.head.appendChild(link);
link.onload = function a() {
console.log("font is onload");
this.onload = null;
this.rel = "stylesheet";
};
font-display: swap;
font-family: HYRunYuan, "PingFang SC";
const url = `https://image-1252680882.cos.ap-shanghai.myqcloud.com/act/2020/HYRunYuan-75W.ttf`;
const HYRunYuan = new FontFace("HYRunYuan", `url(${url})`);
// 添加到全局的 FontFaceSet 中
document.fonts.add(HYRunYuan);
HYRunYuan.load().then(() => {
// 当字体加载完之后,我们就可以通过替换 class 的方法替换掉默认的字体
// 此处的逻辑也可以是你的字体渲染策略
const el = document.querySelector(".flashbuy-area__left");
el.style.fontFamily = "HYRunYuan";
});
const url = `https://image-1252680882.cos.ap-shanghai.myqcloud.com/act/2020/HYRunYuan-75W.ttf`;
window.onload = () => {
console.log("onload");
setTimeout(() => {
const HYRunYuan = new FontFace("HYRunYuan", `url(${url})`);
// 添加到全局的 FontFaceSet 中
document.fonts.add(HYRunYuan);
HYRunYuan.load().then(() => {
// 当字体加载完之后,我们就可以通过替换 class 的方法替换掉默认的字体
// 此处的逻辑也可以是你的字体渲染策略
const el = document.querySelector(".flashbuy-area__left");
el.style.fontFamily = "HYRunYuan";
});
}, 0);
};
最佳实践需根据实际需求来选择,长久看来,方法6 会比较合适,即使没有加载成功,也能展示页面默认字体
如果您有任何问题、建议或合作意向,欢迎通过此表单与我联系。我会尽快回复您的留言。