Dynamically Load fonts

Abhinav picture Abhinav · Jan 25, 2017 · Viewed 13.7k times · Source

I need around 150 fonts for my project. Loading all the fonts initially increases the page load time.

I tried googling but could not find an answer.

Scenario:

User will select a font option from <select> tag. and upon click, I have to retrieve the font dynamically and make sure the font is rendered by the browser and then use the font to avoid a Flash of Unstyled Text (FOUT)

Currently I am using AJAX to request that font file

      $.ajax({
      type: 'GET',
        url: "font-file-url",
        async:false,
        success: function(data) {
            $("style").prepend("@font-face {\n" +
            "\tfont-family: \""+fontValue+"\";\n" + 
            "\tsrc: local('☺'), url("font-file-url") format('opentype');\n" + 
            "}");
         }
      });

Problem

I dont know when exactly the font is being rendered by the browser, so I end up displaying FOUT

Answer

Abhinav picture Abhinav · Jun 29, 2017

May be a bit late, but I accomplished it using Google's WebfontLoader Library. It did the job for me.

This is how I implemented:

Step 1: Include the JS file of the library

Step 2: The below code did the trick for me

WebFont.load({
google: {
  families: ['Droid Sans']
},
timeout:5000,
fontactive: function(familyName,fvd){ //This is called once font has been rendered in browser
    // Your business logic goes here

  },
});

You can also load custom fonts apart from google fonts. Library also provides various callback functions and other cool stuffs. You can check out the above link.