fontfaceobserver 第三方字体加载优化方案

fontfaceobserver 第三方字体加载优化方案

1. github地址

https://github.com/bramstein/fontfaceobserver

2. 基础使用方法
const font = new FontFaceObserver('My Family', {
  weight: 400
});

font.load().then(function () {
  console.log('Font is available');
}, function () {
  console.log('Font is not available');
});
  1. FontFaceObserver:两个参数,第一个font-family必传,第二个option对象,可设置weight、style、stretch等属性;
  2. load方法:开始下载字体返回promise,字体加载成功和失败时分别转为成功和失败态,可在加载字体完成后去使用字体。
  3. load参数,接受两个参数,第一个参数为字符串或null,如果你的字体不包含拉丁字符,你可以通过该参数自定义测试字符串。第二个参数表示加载超时时长,默认3秒,3秒每加载成功即表示字体加载失败,单位为毫秒。
var font = new FontFaceObserver('My Family');

font.load(null, 5000).then(function () {
  console.log('Font is available');
}, function () {
  console.log('Font is not available after waiting 5 seconds');
});
3. 并行加载多种字体
var fontA = new FontFaceObserver('Family A');
var fontB = new FontFaceObserver('Family B');

Promise.all([fontA.load(), fontB.load()]).then(function () {
  console.log('Family A & B have loaded');
});
var exampleFontData = {
  'Family A': { weight: 400, color: 'red' },
  'Family B': { weight: 400, color: 'orange' },
  'Family C': { weight: 900, color: 'yellow' },
  // Etc.
};

var observers = [];

// Make one observer for each font,
// by iterating over the data we already have
Object.keys(exampleFontData).forEach(function(family) {
  var data = exampleFontData[family];
  var obs = new FontFaceObserver(family, data);
  observers.push(obs.load());
});

Promise.all(observers)
  .then(function(fonts) {
    fonts.forEach(function(font) {
      console.log(font.family + ' ' + font.weight + ' ' + 'loaded');

      // Map the result of the Promise back to our existing data,
      // to get the other properties we need.
      console.log(exampleFontData[font.family].color);
    });
  })
  .catch(function(err) {
    console.warn('Some critical font are not available:', err);
  });
  1. 字体加载前,声明字体
const createFontFace2HTMLByTTF = (fontFamily, fontUrl) => {
    if (!fontUrl) {
        return;
    }

    const prevStyle = document.getElementById(fontFamily);

    if (prevStyle) {
        return;
    }
    const style = document.createElement('style');

    style.innerHTML = `
      @font-face {
          font-family: '${fontFamily}';
          src: url(${fontUrl});
    }`;
    // .replace(/\s+/g, ''); 去掉不然有空格的字体名称匹配不上
    style.id = fontFamily;
    document.head.appendChild(style);
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊啊啊~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值