Search code examples
javascriptjquerycssfontsembedded-fonts

Using Javascript to detect if font is installed, then serve different css if it's not


I'm new to Javascript (but not HTML or CSS) and am trying to use this script by Lalit Patel to detect whether a font is installed on the user's system, and if not, to serve a modified style sheet. I've been successful in getting the first part to work: I uploaded the fontdetect.js file, called it in my header, then pasted this before the end of my body tag:

<script type="text/javascript">
window.onload = function() {
    var detective = new Detector();
    alert(detective.detect('Courier'));
};
</script>

(With Courier used as an example.) This causes an alert to pop up on page load telling me whether a font is installed, and works beautifully. But I don't know how to get the script to, instead of triggering an alert, grab a different stylesheet. This seems like basic stuff but I just can't find the specifics anywhere, even though I've been plowing through Javascript tutorials. Any guidance would be greatly appreciated!

If any more specifics are needed: If a user doesn't have the custom font installed or has custom fonts turned off entirely, I'd like to, using CSS change the size/spacing properties of the text so that the fallback font is able to fit in the same space.


Solution

  • After trying all the methods presented, this is the one that worked for me (from this answer, but it's really a mix of the two answers presented here). It should be noted that this works in IE8, unlike most of the other methods (sadly I do need IE8 compatibility).

    <script type="text/javascript">
        window.onload = function() {
            var detective = new Detector();
            if (!detective.detect('Meat')){
                var url = 'link/to/style.css'
                if(document.createStyleSheet) {
                    try { document.createStyleSheet(url); } catch (e) { }
                }
                else {
                    var css;
                    css         = document.createElement('link');
                    css.rel     = 'stylesheet';
                    css.type    = 'text/css';
                    css.media   = "all";
                    css.href    = url;
                    document.getElementsByTagName("head")[0].appendChild(css);
                }
            }
        };
    </script>
    

    This detected that my browser wasn't accepting embedded fonts ("Meat" being one of the fonts I embedded) and served up the alternate CSS (although with a slight delay/flash of unstyled text, maybe because it's at the bottom of the page?) Anyhow, thanks again for all the help!