Created
February 25, 2021 21:46
-
-
Save stephenjwatkins/143404b0a5b2e37c75929a1b6fc93079 to your computer and use it in GitHub Desktop.
Detect when a font loads.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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