cssfontstypekit

Avoid FOUT when using typekit with font events


We are using this to load fonts async with typekit:

<script src="https://use.typekit.net/whatever.js"></script>
<script>try{Typekit.load({async:true});}catch(e){}</script>

But then we had issues with fonts being styled as arial for a split second before the page loads so we hide elements like this (adobe ads this class to elements):

.wf-loading{
    h1, h2, h3, h4, h5, p, a{ 
        visibility: hidden; //hide stuff until adobe gives us the font
    }
}

But what happens if adobe's servers are down, which has happened twice last month for London. Will the elements be unhidden? How do other people manage this issue with typekit?

No information here: https://helpx.adobe.com/typekit/using/font-events.html


Solution

  • Here is a fix to ensure that browser default fonts are displayed if Typekit servers are down.

    <script>
            (function(d) {
                loadFonts = 1;
                if(window.sessionStorage){
                    if(sessionStorage.getItem('useTypekit')==='false'){
                        loadFonts = 0;
                    }
                }
    
                if (loadFonts == 1) {
                        var config = {
                            kitId: 'XXXXXXXX',
                            scriptTimeout: 3000,
                            async: true
                        },
                        h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";if(window.sessionStorage){sessionStorage.setItem("useTypekit","false")}},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+="wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s);
                    }
                }
    
            )(document);
            </script>
    <style>
            .wf-loading p, .wf-loading h1, .wf-loading h2, .wf-loading h3, .wf-loading h4 {
                visibility: hidden;
            }
            .wf-active  p, .wf-active h1, .wf-active h2, .wf-active h3, .wf-active h4 {
                visibility: visible;
            }
            .wf-inactive    p, .wf-inactive h1, .wf-inactive h2, .wf-inactive h3, .wf-inactive h4 {
                visibility: visible;
            }
    </style>
    

    You can read more about the full solution in this blog post.