小程序引入外部字体库 在小程序中引入外部字体库(如自定义字体、iconfont 等),需要注意平台限制和加载性能,不同平台(微信、支付宝、uni-app 等)的实现方式略有差异,但核心思路一致:通过网络链接加载字体文件,或使用小程序平台提供的字体服务。
一、通用引入方法(以微信小程序为例)
1. 使用 @font-face 引入网络字体
将字体文件(如 .ttf、.woff)上传到服务器,通过 @font-face 在样式中定义,然后在页面中使用。
步骤:
-
上传字体文件:将字体文件(如
custom-font.ttf)上传到支持 HTTPS 的服务器,获取访问链接(如https://example.com/fonts/custom-font.ttf)。 -
在样式中定义:在页面的
.wxss或全局app.wxss中声明字体:/* 定义字体 */ @font-face { font-family: 'CustomFont'; /* 自定义字体名称 */ src: url('https://example.com/fonts/custom-font.ttf') format('truetype'); /* 可选:添加其他格式兼容不同浏览器 */ /* src: url('xxx.woff') format('woff'), url('xxx.woff2') format('woff2'); */ } /* 使用字体 */ .custom-text { font-family: 'CustomFont', sans-serif; } -
在页面中使用:
<view class="custom-text">这是使用自定义字体的文本</view>
2. 引入 iconfont 图标字体
阿里的 iconfont 是常用的图标字体库,引入方式如下:
步骤:
-
下载 iconfont 资源:在 iconfont 官网 选择图标,生成并下载字体包(含
.ttf、.woff、iconfont.css等)。 -
上传字体文件:将
.ttf等字体文件上传到服务器,获取网络链接。 -
修改 iconfont.css:将
iconfont.css中的本地路径替换为网络链接,然后在小程序中引入:/* 引入修改后的 iconfont.css */ @import url('/styles/iconfont.css'); /* 或直接在样式中定义 */ @font-face { font-family: 'iconfont'; src: url('https://example.com/fonts/iconfont.ttf') format('truetype'); } .iconfont { font-family: 'iconfont' !important; font-size: 16px; font-style: normal; -webkit-font-smoothing: antialiased; } -
使用图标:
<text class="iconfont"></text> <!-- 使用 Unicode 编码 --> <text class="iconfont icon-xxx"></text> <!-- 使用 class 名称 -->
二、uni-app 引入外部字体
uni-app 支持跨平台引入字体,需注意不同平台的差异:
1. 网络字体引入(推荐)
与微信小程序类似,通过 @font-face 引入网络字体,兼容多平台:
/* 在 App.vue 或页面样式中定义 */
@font-face {
font-family: 'CustomFont';
src: url('https://example.com/fonts/custom-font.ttf') format('truetype');
}
/* 使用 */
.text {
font-family: 'CustomFont';
}
2. 本地字体引入(需注意平台限制)
-
H5 平台:可直接将字体文件放在项目
static目录,使用相对路径:@font-face { font-family: 'CustomFont'; src: url('/static/fonts/custom-font.ttf') format('truetype'); } -
微信 / 支付宝小程序:本地字体文件大小有限制(通常不超过 400KB),且需通过
wx.loadFontFace动态加载(uni-app 中对应uni.loadFontFace):// 在页面 onLoad 中加载 onLoad() { uni.loadFontFace({ family: 'CustomFont', source: 'url("/static/fonts/custom-font.ttf")', success() { console.log('字体加载成功'); }, fail(err) { console.log('字体加载失败', err); } }); }
三、注意事项
-
字体文件大小限制:
- 微信小程序:本地字体文件需 ≤ 400KB,超过需用网络链接加载。
- 支付宝小程序:网络字体无明确限制,但建议压缩字体(如通过 Font Squirrel 精简字符)。
-
HTTPS 协议:网络字体链接必须使用
HTTPS,否则在小程序中会被拦截。 -
加载性能:大字体文件会导致页面加载缓慢,建议:
-
只保留必要字符(如图标字体只包含使用的图标)。
-
使用
woff2格式(比ttf体积小约 30%)。 -
配合
font-display: swap优化加载体验:@font-face { font-family: 'CustomFont'; src: url('xxx.ttf') format('truetype'); font-display: swap; /* 字体加载完成前显示默认字体 */ }
-
-
平台兼容性:
-
微信小程序不支持
local()引入本地字体,需用uni.loadFontFace或网络链接。 -
字节跳动(抖音)小程序对网络字体有严格限制,建议优先使用平台提供的字体库。
-
通过以上方法,可在小程序中灵活使用外部字体库,提升界面个性化程度,但需平衡加载性能和兼容性。