Solution to font loading failure caused by cross-domain mini program font files, especially for Android

Load font scheme

If you are using the mobile phone, you need to use the loadFontFace API to load font files. You can use uniapp or WeChat. For usage instructions, see the official website instructions:uni.loadFontFace(Object object ) | uni-app official website

If you use the css loading method, you may not be able to locate the cause of the font failure bug. However, loadFontFace has an interface for loading failure, so you can check the cause of the error. The following is the method of loading fonts with css. It is not recommended.

@font-face {
    font-family: 'hado-font';
    src: url('https://字体文件链接');
}

Use the api code of loadFontFace: Use it in the onLunch hook function in app.vue

  // 加载网络字体
  uni.loadFontFace({
    family: 'hado-font',
    global: true,
    source: 'url("https://你的域名字体文件地址")',
    success() {
      console.log('hado-font加载成功')
    },
    fail(err) {
      console.log('hado-font加载失败', err)
    },
    complete() {
      console.log('hado-font字体加载');
    }
  })

Problem recurrence

Font loading failed and did not take effect: This problem mainly exists in Android mobile applets and h5 end. Apple mobile applets do not seem to exist, but the reason for the problem is the same, that is, cors cross-domain occurs: The following is cross-domain on the h5 side

On the Android mobile phone, the following error will be reported: "loadFontFace:fail", which does not indicate that it is caused by cross-domain. However, if there is no problem with your font files and links, it is caused by cross-domain.

 

solution

Prerequisite note: The font file link must be https, and the font file must be able to be used normally. Add the domain name to the downloadFile legal domain name list in the mini program background. It is recommended to also add the link to the request legal domain name list.

1. Configure on the server or nginx to allow cross-domain. I do this by configuring nginx cross-domain. Find the nginx configuration file, and then add an nginx configuration:

location ~ .*\.(eot|otf|ttf|woff|woff2|svg)$
{
  add_header Access-Control-Allow-Origin *;
}

Check whether the configuration is correct: ok and success indicate no problem

 sudo nginx -t

After the configuration is OK, you need to reload the configuration file and restart nginx: make the configuration file take effect

nginx -s reload

 Then I reopened it and found that the font was loaded successfully: as long as there is no problem with h5, the Android phone will also be fine.

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/134965082