Improving Google Page Speed Insights Score: Loading Custom Fonts

Posted:

The best way to load a custom fonts is to use a JavaScript plugin called Web Font Loader, developed by both Google & Adobe Typekit

The custom fonts can either be loaded in from one of the 3 main remote custom font services (Google Fonts, Fonts.com, or, Adobe Typekit), or we can even load one in locally if we have the right files (this counts for icon fonts too like FontAwesome!).

Here is an example of how I deal with loading Google fonts in my <head> element:

// Add wf-loading class to html element straight away so we can hide/show fonts that aren't styled straight away
document.documentElement.className += " wf-loading";

// Web font loader
WebFontConfig = {
    // Google Fonts
    google: {
        families: [
            'Lato:300,300i,400,700,700i:latin', // Lato font with several weights
            'Material+Icons' // Google's icon font
        ]
    },
    // Fonts.com
    monotype: {
        projectId: 'xxxxxx-xxx-xxx-xxx-1337'
    },
    // Custom fonts
    custom:{
        families: ["FontAwesome"], // Array of Font Family names for the local custom fonts that are loaded in
        urls: ["/resources/vendor/font-awesome/css/font-awesome.min.css"], // Array of paths to the .css files which is loading in the custom local font
    }
};
(function() {
    var wf = document.createElement('script');
    wf.src = '/resources/vendor/webfontloader/1.6.26/webfontloader.min.js'; // Path to webfont loader, this can be local or loaded through cdn
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
})();