I like using WebFontLoader to load fonts. It's a quick solution that has worked well for me. I typically use it asynchronously by putting something like this in my page <head>
:
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js" async></script>
WebFontConfig = {
google: {
families: ['Droid Sans', 'Droid Serif']
}
};
Then, in my CSS, I'll do something like this:
h1 {
font-family: 'Droid Sans', Helvetica, Arial, sans-serif;
}
I've been reading lately about WebFontLoader, though, and most of the examples I see (here's one article about it) instead do something like this, using the classes that WFL applies to the <html>
element to detect whether the font is loaded and ready for use:
h1 {
font-family: Helvetica, Arial, sans-serif;
.wf-active & {
font-family: 'Droid Sans', Helvetica, Arial, sans-serif;
}
}
My question is: Why is declaring a normal font stack with system backups not enough? Isn't the point of font-family so that if the first one isn't recognized, it will automatically fall back to the others?
If browsers see that the first font in the stack is not a system one, will it by default hide that element, despite there being backups -- or something like that?
Why is declaring a normal font stack with system backups not enough?
It is enough, if all you want to do is use your fonts once they're all available. But maybe you'd like to do more the moment you are guaranteed your fonts are ready for use, and in that case using a CSS class helps do far more powerful things. As such, most examples will show you the "more power" version rather than the limited use case: using a class on the <html>
element lets you trigger any functionality and restyling that you might want to have kick in when the webfonts are ready.
For instance, you can use it as a switch to turn off a dialog that should only be visible as long as your webfonts aren't ready. E.g.::
<html>
...
<div class="font-loading">Please wait while the fonts load.</div>
...
</html>
with some form of CSS that does
.font-loading {
background: red;
color: white;
border: 1px solid black;
opacity: 1;
height: 4em;
transition: opacity 1s ease-in, height 1s ease-in;
}
.wf-active .font-loading {
opacity: 0;
height: 0;
}
Having that wf-active
class added to the <html>
element explicitly gives your whole page a signal that can be used to "do things that need to happen when all my webfonts are ready for use", which is something very different from just "using fonts once they are ready".