Saturday, March 19, 2016

How to optimize Google Fonts load

When using Google Fonts, or any other custom fonts, many users might find an usual and irritating problem: the page doesn't render until the fonts are loaded. The page keeps blank during 2 or more critical seconds while the system fetches the required font files.

There are many ways to solve it but they usually are very complicated. Here I bring you a really easy way to solve it.

What I wanted to do is simply load the page with the default browser fonts (sans, arial or any other) and once is has been rendered, start to request the custom fonts to the server.

The solution is really straightforward:

Firstly create a CSS class for the text sections with the font that you want to use and present the HTML tags without that style:
h1.styled
{
    font-family: "Rhodium Libre";
}

Then add the following JQuery code in the header of your page:
<SCRIPT TYPE="text/javascript">
    $(document).ready(function()
    {
        $('head').append("<link href='https://fonts.googleapis.com/css?family=Rhodium+Libre' rel='stylesheet' type='text/css'>");
        $('h1').addClass('styled');
    }); 
</SCRIPT>

That's it. What we are doing is to render the h1 tags by default showing the texts immediately and once it's loaded, we look for the Google fonts and apply the style to our text sections.