Skip to content

Instantly share code, notes, and snippets.

@AllThingsSmitty
Last active October 22, 2021 20:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllThingsSmitty/bac8cc1e7cf93741ae45 to your computer and use it in GitHub Desktop.
Save AllThingsSmitty/bac8cc1e7cf93741ae45 to your computer and use it in GitHub Desktop.
Progressively loading fonts with font events
// Eliminate FOIT (Flash of Invisible Text) caused by web fonts loading slowly
// Using font events with Font Face Observer
var roboto = new FontFaceObserver('Roboto', {
weight: 400
});
observer.check().then(function () {
document.getElement.className += 'fonts-loaded';
});
// Load multiple fonts using a Promise
var roboto400 = new FontFaceObserver('Roboto', {
weight: 400
});
var roboto500 = new FontFaceObserver('Roboto', {
weight: 500
});
var roboto700 = new FontFaceObserver('Roboto', {
weight: 700
});
Promise.all([
roboto400.check(),
roboto500.check(),
roboto700.check()
]).then(function () {
document.documentElement.className += ' fonts-loaded';
}, function () {
// Use the catch to give the html element a unique class name to handle the timeout state
document.documentElement.className += ' fonts-unavailable';
});
/* Eliminate FOUT (Flash of Unstyled Text) caused by web fonts loading slowly */
@font-face {
font-family: "RobotoLocal";
font-style: normal;
font-weight: 400;
src: local("Roboto"),
local("Roboto-Regular");
}
body {
font-family: "RobotoLocal", Helvetica, Arial, sans-serif; /* fallback font: Helvetica */
}
.fonts-loaded body {
font-family: "Roboto", Helvetica, Arial, sans-serif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment