Skip to content

Instantly share code, notes, and snippets.

@shrekuu
Created May 27, 2019 07:47
Show Gist options
  • Save shrekuu/ecd0caab09b22a63100f99bf97862f0f to your computer and use it in GitHub Desktop.
Save shrekuu/ecd0caab09b22a63100f99bf97862f0f to your computer and use it in GitHub Desktop.
小程序动态加载 fontawesome 字体图标
import environment from './environment'
// 把字体资源放到后端服务器上
// 使这样可以访问到 ${environment.baseURL}/vendor/fontawesome-5.8/webfonts/fa-regular-400.woff
// 服务器要上 https + CORS
// 更多参考: https://developers.weixin.qq.com/miniprogram/dev/api/wx.loadFontFace.html
// 如果实在不稳定, 就使用 http://fontello.com/ 生成 base64 样的字体内嵌风格 css 使用
// 尝试动态加载的字体图标
const fontAwesomeFonts = [
{
family: 'Font Awesome 5 Free',
desc: {
weight: 'normal',
},
source: `url("${environment.baseURL}/vendor/fontawesome-5.8/webfonts/fa-regular-400.woff")`,
loaded: false,
},
{
family: 'Font Awesome 5 Free',
desc: {
weight: 'bold',
},
source: `url("${environment.baseURL}/vendor/fontawesome-5.8/webfonts/fa-solid-900.woff")`,
loaded: false,
},
{
family: 'Font Awesome 5 Brands',
source: `url("${environment.baseURL}/vendor/fontawesome-5.8/webfonts/fa-brands-400.woff")`,
loaded: false,
},
]
// 轮询判断字体是否加载成功, 没有成功就继续尝试加载
// todo: 发现即使加载成功后也无法稳定地在所有页面显示, 放弃动态加载字体
export function ensureFontAwesomeFontsLoaded () {
setTimeout(() => {
loadFontAwesomeFonts()
}, 200)
const loadFontAwesomeFontsIntervalId = setInterval(() => {
if (fontAwesomeFonts.some(e => !e.loaded)) {
loadFontAwesomeFonts()
} else {
clearInterval(loadFontAwesomeFontsIntervalId)
}
}, 2000)
}
// 加载字体
function loadFontAwesomeFonts () {
const brutalLoadFont = (options, index) => {
setTimeout(() => {
wx.loadFontFace({
...options,
success: res => {
console.log('fontawesome fonts loading success', res)
fontAwesomeFonts[index].loaded = true
},
fail: err => {
console.log('fontawesome fonts loading fail', err)
brutalLoadFont(options)
},
})
}, 1)
}
fontAwesomeFonts.forEach((e, i) => {
if (!e.loaded) {
brutalLoadFont(e, i)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment