Apps optimize

How to use the Google WebFont Loader

Ryan Boudreaux shows how to use the Google WebFont Loader and illustrates some basic configuration.

In a previous segment I reviewed the quick and easy way to incorporate Google Web Fonts into your websites. In this post I will review the advanced features of the Google WebFont Loader, which is the JavaScript library that provides you with more control for loading Google Web Fonts API, and allows you to use multiple web-font providers, which was co-developed with Typekit. Using the WebFont Loader does require some knowledge of JavaScript; however, I will review these advanced techniques in this segment and demonstrate its use along with a download which is available at the bottom of this post.

Overview

The Google WebFont Loader is part of the Google Hosted Libraries, which is a content distribution network for the Google Developers open-source JavaScript libraries. The WebFont Loader is currently at version 1.0.30, and it provides events that are fired at different stages of the loading of the fonts. You can either write your own code to react to those events, or use CSS styles defined by the library to automatically make styles change when the fonts have finished loading in the browser.

The following code snippet gets added to the <head> section of your web document to load the JavaScript and includes the most recent version, which has the added benefit of serving a longer cache duration and shorter loading time:

(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);
 })();

Configuration

The WebFont Loader configuration is defined by a global variable named WebFontConfig when loading the script asynchronously, and when using this approach, you must define the global variable WebFontConfig before the code above that loads the WebFont Loader. Use the configuration variable to specify the font source provider and the font families to be loaded into your web pages. The example code snippet below shows the configuration for loading the Google Web Fonts API for 'Aclonica', 'Acme', and 'Alegreya', three trending and popular font selections:

WebFontConfig = {
  google: { families: [ 'Aclonica', 'Acme', 'Alegreya' ]
       }
};

Other font providers

Options for loading fonts from other providers include the following provider examples with the WebFontConfig for TypeKit, Ascender Fonts Alive, Fonts.com, and Font Deck.

TypeKit:

WebFontConfig ={
  typekit: {
    id: 'myKitId'
  }
};

Ascender - Fonts Alive:

WebFontConfig ={
  ascender: {
    key: 'myAscenderKey',
    families: [ 'AscenderSans:bold,bolditalic,italic,regular' ]
  }
};

Fonts.com Web Fonts:

WebFontConfig ={
  monotype: {
    projectId: 'YourProjectId'
  }
};

Fontdeck:

WebFontConfig = {
  fontdeck: {
    id: 'xxxxx'
  }
};

You can also specify multiple font source providers in a single web font configuration variable with each source separated by a comma as in the following example:

WebFontConfig = {
  google: {
    families: ['Aclonica', 'Acme', 'Alegreya']
  },
  typekit: {
    id: 'myKitId'
  },
  ascender: {
    key: 'myAscenderKey',
    families: [ 'AscenderSans:bold,bolditalic,italic,regular' ]
  },
  monotype: {
    projectId: 'YourProjectId'
  }
};

Putting it all together

When we put it all together the JavaScript code snippet should look like this example shown below:

<script type="text/javascript">
    WebFontConfig = {
    google: { families: [ 'Aclonica', 'Acme', 'Alegreya' ]
       }
    };
    (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);
   })();
</script>

Applying styles

The WebFont loader will process the fonts using the following event order as the browser downloads them or puts them into cache:

  1. Fonts start to download specified with the class of .wf-loading
  2. Once the fonts are loaded they are given the class of .wf-active
  3. If fonts fail to load then they are given a class of .wf-inactive

This demonstration includes three fonts, therefore the WebFont Loader will trigger events for each of the three individual fonts, and for all the fonts as a whole. The WebFont Loader alerts you to each of the three events listed above in two methods: it requests distinct CSS classes when each event happens, and by triggering specified JavaScript events. For this demonstration, we'll be exercising the CSS classes as shown in the code snippet below for each of the load events:

.wf-loading p { font-family: sans-serif; }
.wf-inactive p { font-family: sans-serif; }
.wf-active p { font-family: 'Alegreya', sans-serif; width:400px; margin-left:20px; }
.wf-loading h1 { font-family: sans-serif; font-weight: 400; font-size: 24px; }
.wf-inactive h1 { font-family: sans-serif; font-weight: 400; font-size: 24px; }
.wf-active h1 { font-family: 'Aclonica', sans-serif; font-weight: 400; font-size: 24px; }
.wf-loading h2 { font-family: sans-serif; font-weight: 300; font-size: 20px; color:#5E5E5E; }
.wf-inactive h2 { font-family: sans-serif; font-weight: 300; font-size: 20px; color:#5E5E5E; }
.wf-active h2 { font-family: 'Acme', sans-serif; font-weight: 300; font-size: 20px; color:#5E5E5E; }
The active output with sample HTML is displayed in Figure B below:

Figure B

As the page is loading you will see that the headings and paragraph are rendered sans-serif and the paragraph also extends across the entire page, as displayed in Figure C. And once the class .wf-active does become active in the browser for each style it will render the active styling for each class as originally shown in Figure B above.

Figure C

The Google Module

The Google Module also allows you to specify specific weights and styles with the WebFont Loader using the Google Web Fonts API syntax. An example code snippet of the web font configuration below is one way to request the font Yanone Kaffeesatz bold and Droid Serif italic, as displayed below:

WebFontConfig = {
  google: {
    families: [ 'Yanone Kaffeesatz:700', 'Droid Serif:italic' ]
  }
};

Acting on events

If you want to get more in-depth with loading events, then you can use the asynchronous method, where the WebFont Loader starts loading the fonts defined in the WebFontConfig object as soon as the script has loaded. If you want even more control than the CSS classes provide as demonstrated in the examples above, then you can specify your own callbacks that will be requested when certain events fire, which happens when the loading reaches a certain defined state.

The source code for the Google WebFont Loader is available from the GitHub resource.

The HTML and CSS code demonstrated in this tutorial is available for download.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

0 comments