Dynamically load google fonts after page has loaded

Alexis picture Alexis · May 14, 2013 · Viewed 20.4k times · Source

I would like to be able to have the user select which font they would like the page to be displayed in. Here is the way that Google recommends you do it using JavaScript.

WebFontConfig = {
    google: {
        families: ['Tangerine', 'Cantarell']
    }
};

(function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
            '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })();

How can I modify this so that I can re-get fonts after the page has loaded?

Answer

mccannf picture mccannf · May 15, 2013

Check out the WebFont.load command in this github repo:

https://github.com/typekit/webfontloader

You can load whatever font you want dynamically:

 <script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script> 
  <script> 
        WebFont.load({
                    google: { 
                           families: ['Droid Sans', 'Droid Serif'] 
                     } 
         }); 
   </script>