JavaScript/CSS Font Detector

JavaScript code to detect available availability of a particular font in a browser using JavaScript and CSS.

Update: I have updated the algo of the script and it is almost 100% accurate.

This JavaScript class can be used to guess if a particular font is present in a machine. This may be help of desktop-like web application developers when they want to provide different skins or fonts preferences to their users. This may also be help for blog skin designers which can provide different fonts for different users based on the list of fonts on their machine. Designers don’t have to rely on the most common fonts like Arial, Verdana or Times New Roman. Since increasing number of users
have modern PC with new operating system / applications, they may very well have a wide array of other common fonts in their machine.

How does it work?

This code works on the simple principle that each character appears differently in different fonts. So different fonts will take different width and height for the same string of characters of same font-size.

Widths of same text in different fonts

We try to create a string with 3 generic font-face, monospace, sans-serif and sans and note their width. Then try to create the same string in HTML using the font to be tested and the generic fallback font. If the font-face is not available, it takes up the generic fallback font-face. We then compare the width of the string with the new font and width of the string with the fallback generic font-face, if they are different, then the font exists, otherwise not.

<span style="font-family: monospace; font-size: 72px">mmmmmmmmmmlli</span>
vs.
<span style="font-family: New-Font, monospace; font-size: 72px">mmmmmmmmmmlli</span>

Since this test is repeated three times against 3 font families, it gives almost 100% accurate results. The string which we will use to generate the widths can be anything. But I guess we use ‘m’ or ‘w’ because these two characters take up the maximum width. And we use a trailing ‘l’ and ‘i’ so that the same width fonts-faces can get separated based on the width of l character. I have tested it on Firefox, IE, Opera, Safari, Chrome

Note:
It required to execute the script after its completely loaded for some browsers like Opera. (Opera cannot calculate the offsetWidth until all the parents are completely loaded)

Download ver 0.3 (24 Mar 2012)

Released under Apache Software License 2.0.

Plain text JS code (v0.3)

Demo

You can test any Font here:

// Usage
window.onload = function() {
    var detective = new Detector();
    alert(detective.detect('font name'));
};

Fonts on your computer

This table below shows which fonts are present on your system. (I have listed some of the most common and some uncommon fonts.)

Font Name Detected?