O Font Face Observer é um pequeno carregador e monitor @font-face
(3,5kb minificado e 1,3kb gzipped) compatíveis com qualquer serviço webfont. Ele monitorará quando um webfont for carregado e notificá -lo. Ele não o limita de forma alguma em onde, quando ou como você carrega seus webfonts. Diferentemente do Observador Facial do Loader Font Font, usa eventos de rolagem para detectar cargas de fonte com eficiência e com sobrecarga mínima.
Inclua suas regras @font-face
como de costume. As fontes podem ser fornecidas por um serviço de fonte, como Google Fontes, TypeKit e WebType ou serem auto-hospedados. Você pode configurar o monitoramento de uma única família de fontes por vez:
var font = new FontFaceObserver ( 'My Family' , {
weight : 400
} ) ;
font . load ( ) . then ( function ( ) {
console . log ( 'Font is available' ) ;
} , function ( ) {
console . log ( 'Font is not available' ) ;
} ) ;
O construtor FontFaceObserver
leva dois argumentos: o nome da família da fonte (exigido) e um objeto que descreve a variação (opcional). O objeto pode weight
propriedades, style
e stretch
. Se uma propriedade não estiver presente, ela não será normal
. Para começar a carregar a fonte, chame o método load
. Ele retornará imediatamente uma nova promessa que resolve quando a fonte for carregada e rejeitada quando a fonte não conseguir carregar.
Se sua fonte não contiver pelo menos os caracteres latinos "Besbwy", você deve passar uma sequência de teste personalizada para o método load
.
var font = new FontFaceObserver ( 'My Family' ) ;
font . load ( '中国' ) . then ( function ( ) {
console . log ( 'Font is available' ) ;
} , function ( ) {
console . log ( 'Font is not available' ) ;
} ) ;
O tempo limite padrão para desistir do carregamento da fonte é de 3 segundos. Você pode aumentar ou diminuir isso passando vários milissegundos como o segundo parâmetro para o método load
.
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' ) ;
} ) ;
Múltiplas fontes podem ser carregadas criando uma instância FontFaceObserver
para cada um.
var fontA = new FontFaceObserver ( 'Family A' ) ;
var fontB = new FontFaceObserver ( 'Family B' ) ;
fontA . load ( ) . then ( function ( ) {
console . log ( 'Family A is available' ) ;
} ) ;
fontB . load ( ) . then ( function ( ) {
console . log ( 'Family B is available' ) ;
} ) ;
Você também pode carregar os dois ao mesmo tempo, em vez de carregar cada um individualmente.
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' ) ;
} ) ;
Se você estiver trabalhando com um grande número de fontes, pode decidir criar instâncias FontFaceObserver
dinamicamente:
// An example collection of font data with additional metadata,
// in this case “color.”
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 ) ;
} ) ;
O exemplo a seguir emula o Fout com o Font Face Observer para My Family
.
var font = new FontFaceObserver ( 'My Family' ) ;
font . load ( ) . then ( function ( ) {
document . documentElement . className += " fonts-loaded" ;
} ) ;
. fonts-loaded {
body {
font-family : My Family , sans-serif;
}
}
Se você estiver usando o NPM, você pode instalar o Observer Facs Face como uma dependência:
$ npm install fontfaceobserver
Você pode exigir fontfaceobserver
como um módulo CommonJS (BrowSerify):
var FontFaceObserver = require ( 'fontfaceobserver' ) ;
var font = new FontFaceObserver ( 'My Family' ) ;
font . load ( ) . then ( function ( ) {
console . log ( 'My Family has loaded' ) ;
} ) ;
Se você não estiver usando o NPM, pegue fontfaceobserver.js
ou fontfaceobserver.standalone.js
(veja abaixo) e inclua -o no seu projeto. Ele exportará um FontFaceObserver
global que você pode usar para criar novas instâncias.
O Font Face Observer usa promessas em sua API; portanto, para os navegadores que não suportam promessas, você precisará incluir um poli -preenchimento. Se você usar sua própria promessa Polyfill, só precisará incluir fontfaceobserver.standalone.js
em seu projeto. Se você não possui um Polyfill Promise Existing, use fontfaceobserver.js
, que inclui um poli -preenchimento de pequenas promessas. O uso do Promise Polyfill adiciona aproximadamente 1,4kb (500 bytes gzipped) ao tamanho do arquivo.
O FontfaceObServer foi testado e trabalha nos seguintes navegadores:
O Observador Facial de Fonte está licenciado sob a licença BSD. Copyright 2014-2017 Bram Stein. Todos os direitos reservados.