Reputation:
After having read this article about the best ways to serve web fonts, I wanted to make use of the recent javascript library Font Face Observer to load Google fonts asynchronously on my website.
The documentation reads that "fonts can be supplied by [...] a font service such as Google Fonts", but it doesn't show any examples on how to actually implement this. I've read the recommended articles about the Font Face Observer listed on the official website, but all of them showed how to use it with self-hosted fonts.
Did anyone use the Font Face Observer to load Google fonts? Or, could you point me to some documentation that shows how to approach this?
Upvotes: 2
Views: 4758
Reputation: 176
I've used such an approach in order to achieve fonts lazy-loading. You have to make sure your Google font is added to the stylesheet link. After that use FontFaceObserver as usual - just pass Google font name as an argument to create a new FontFaceObserver instance. To manage my Google fonts I've used a tiny helper google-fonts.
Code sample will look like this:
import googleFonts from 'google-fonts';
import FontFaceObserver from 'fontfaceobserver';
loadGoogleFont(fontName) {
googleFonts.add({[fontName]: true}); // or some other options if you need
const fontObserver = new FontFaceObserver(fontName);
return fontObserver.load()
.catch(err => console.log(fontName, err));
}
Upvotes: 3
Reputation: 1403
This is a fairly simple way I have used it, though I'm unsure if it's the best way. The reason such an approach may be good is that the font loading does not block render since I have the script in my JS file at the end. So basically I start loading the font as soon as my JS file starts parsing and it gets rendered as soon as it's loaded.
import FontFaceObserver from 'fontfaceobserver'
import loadCSS from './util/loadCSS'
loadCSS('//fonts.googleapis.com/css?family=Open+Sans:300,400,400i,600,700')
const opensans = new FontFaceObserver('Open Sans')
opensans.load().then(() => document.body.classList.add('fonts--loaded'))
Upvotes: 1