Skip to content

Instantly share code, notes, and snippets.

@stephenjwatkins
Created February 25, 2021 21:46
Show Gist options
  • Save stephenjwatkins/143404b0a5b2e37c75929a1b6fc93079 to your computer and use it in GitHub Desktop.
Save stephenjwatkins/143404b0a5b2e37c75929a1b6fc93079 to your computer and use it in GitHub Desktop.
Detect when a font loads.
function onFontLoaded(fontFamily) {
const font = `1rem ${fontFamily}`;
return new Promise((resolve, reject) => {
const isFontAvailable = document.fonts.check(font);
if (isFontAvailable) {
resolve();
} else {
document.fonts.ready
.then(() => {
if (document.fonts.check(font)) {
resolve();
} else {
reject(new Error("Unable to resolve font"));
}
})
.catch(reject);
}
});
}
// Example of use
onFontLoaded("Material Icons")
.then(() => {
console.log("Material Icons has loaded");
}).catch(error => {
console.log("Problem loading Material Icons");
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment