Check if a Font is Available on a Web Page with JavaScript
I'm working on a page that provides some font tools1. Part of the functionality requires knowing if a given font is available on the page or not. This is the function I'm using to check that.
Example
Here's an example using bitty for the display. is a stand-alone function. It doesn't require bitty. I'm just using it to make the output simpler.
Output
HTML
Notes
-
The process works by making a transparent div with a piece of text in it. The text is set to the browsers generic
font and the width is measured. The font is then changed to the name of the requested font withas a fallback and measured again.If the font is available and loads the two width values have a very high probability of being different sizes. When a difference is detected the value of the return payload is
true. -
The measurement values on my machine go to seven significant digits. It's possible that the target font produces the exact same width as the generic. If that happens, the response value of the payload would be
falseeven though the font is available. - I'm not aware of a way in which false positives are possible.
- The text string is a randomly generated UUID consisting of 36 characters. That size helps encourage a difference between the measured values. It also means you could do multiple checks to reduce the chance of false negatives.
- Other examples I've seen suggest using documents.fonts and FontFaceSet: check(). That doesn't work as expected because Nonexistent fonts return true.
-
The
document..does come into play to make sure that any external fonts have been loaded before running the checks. - Another example I saw created a canvas to do the sizing. It does effectively the same thing but with a larger overhead.
-
The return value from the function is an object in one of three possible states.
It's used to checking for the
valuekey. It it exists, the function completed successfully and return a specific response. If theerrorkey is returned instead it means the function failed. The font may or may not be available.
Tests
These tests are dependent on the specific fonts being available. They'll produce false failures if they aren't.
Output
HTML
Wrap-up
Solving this took several hours. It feels like one of those things that should be easier. Maybe one day it will be. For now, this does what I need.
-a
Endnotes
The function uses features listed as being available in all major browsers. I checked it in my versions of
- Chrome on Mac
- Chrome on Windows 10
- Edge on Window 10
- Firefox on Mac
- Firefox on Windows 10
- Safari on Mac
- Safari on iOS
References
The cursive generic font name has been around since very early versions of the major browsers.
Footnotes
A place to put some details about font normalization. Under construction at the time of this writing.