Font Face Observer es un pequeño cargador y monitor @font-face
(3.5kb minificado y 1.3kb GZipped) compatible con cualquier servicio webfont. Monitoreará cuando se cargue una fuente web y le notifique. No lo limita de ninguna manera en dónde, cuándo o cómo carga sus infts web. A diferencia del observador de la fuente del cargador de fuente web, el observador de la cara utiliza eventos de desplazamiento para detectar cargas de fuentes de manera eficiente y con una sobrecarga mínima.
Incluya sus reglas @font-face
como de costumbre. Las fuentes pueden ser suministradas por un servicio de fuentes como Google Fonts, Typekit y WebType o ser autohostados. Puede configurar el monitoreo de una sola familia de fuentes a la 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' ) ;
} ) ;
El constructor FontFaceObserver
toma dos argumentos: el nombre de la familia Font (requerido) y un objeto que describe la variación (opcional). El objeto puede contener propiedades de weight
, style
y stretch
. Si una propiedad no está presente, se predeterminará a normal
. Para comenzar a cargar la fuente, llame al método load
. Inmediatamente devolverá una nueva promesa que se resuelve cuando la fuente se carga y rechazará cuando la fuente no se carga.
Si su fuente no contiene al menos los caracteres latinos "besbwy", debe pasar una cadena de prueba personalizada al 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' ) ;
} ) ;
El tiempo de espera predeterminado para renunciar a la carga de fuente es de 3 segundos. Puede aumentar o disminuir esto pasando varios milisegundos como el segundo parámetro al 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' ) ;
} ) ;
Se pueden cargar múltiples fuentes creando una instancia FontFaceObserver
para cada una.
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' ) ;
} ) ;
También puede cargar ambos al mismo tiempo, en lugar de cargar cada uno 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' ) ;
} ) ;
Si está trabajando con una gran cantidad de fuentes, puede decidir crear instancias FontFaceObserver
dinámicamente:
// 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 ) ;
} ) ;
El siguiente ejemplo emula con 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;
}
}
Si está utilizando NPM, puede instalar Font Face Observer como dependencia:
$ npm install fontfaceobserver
Luego puede requerir fontfaceobserver
como un módulo CommonJS (Browserify):
var FontFaceObserver = require ( 'fontfaceobserver' ) ;
var font = new FontFaceObserver ( 'My Family' ) ;
font . load ( ) . then ( function ( ) {
console . log ( 'My Family has loaded' ) ;
} ) ;
Si no está usando NPM, obtenga fontfaceobserver.js
o fontfaceobserver.standalone.js
(ver más abajo) e incluya en su proyecto. Exportará un FontFaceObserver
global que puede usar para crear nuevas instancias.
Font Face Observer utiliza promesas en su API, por lo que para los navegadores que no admiten promesas que deberá incluir un polyfill. Si utiliza su propio prometedor, solo necesita incluir fontfaceobserver.standalone.js
en su proyecto. Si no tiene una promesa existente, debe usar fontfaceobserver.js
lo que incluye un pequeño prometedor polyfill. El uso del Polyfill Promise agrega aproximadamente 1.4kb (500 bytes Gzipped) al tamaño del archivo.
FontFaceObServer ha sido probado y funciona en los siguientes navegadores:
Font Face Observer tiene licencia bajo la licencia BSD. Copyright 2014-2017 Bram Stein. Reservados todos los derechos.