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');
});
- FontFaceObserver:两个参数,第一个font-family必传,第二个option对象,可设置weight、style、stretch等属性;
- load方法:开始下载字体返回promise,字体加载成功和失败时分别转为成功和失败态,可在加载字体完成后去使用字体。
- 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);});
- 字体加载前,声明字体
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);
};