O'Reilly

Google Font API

By on  

Google recently debuted a new web service called the Font API.  Google's Font API provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let's take a quick look at the ways by which the Google Font API can be used.

Font Request Format

Many of the fonts within Google's font archive are available not only in standard format but also in Italic, Bold, and Italic Bold.  The format for requesting a given font variant is:

{font}:{variant1},{variant2}

Here are a few examples of requesting each variant:

Cantarell
Cantarell:bold
Cantarell:italic
Cantarell:bolditalic

Now let's see how we can include special fonts in our page and use these them.

The CSS Stylesheet Method

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Cantarell" />

The stylesheet gets included into the page like any other stylesheet would be.  A query string with a family parameter is appended to the stylesheet's URL containing the font(s) to be loaded.  Multiple fonts can be requested with the use of the "|" (pipe) character.  A few examples:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn:bold" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn|IM+Fell+Great+Primer" />

Take a moment to examine the stylesheet from Google:

@font-face {
	font-family: 'IM Fell Great Primer';
	font-style: normal;
	font-weight: normal;
	src: local('IM Fell Great Primer'), url('http://themes.googleusercontent.com/font?kit=AL8ALGNthei20f9Cu3e93rvDyRCRMn38Ifm6ee4fjno') format('truetype');
}
@font-face {
	font-family: 'Vollkorn';
	font-style: normal;
	font-weight: normal;
	src: local('Vollkorn'), url('http://themes.googleusercontent.com/font?kit=_3YMy3W41J9lZ9YHm0HVxA') format('truetype');
}

The @font-face method of font embedding is Google's chosen method.  Using the font is as simple as using a system font:

.mySpecialFontClass	{ font-family:'Vollkorn', serif; }

You may also embed the font within the "style" attribute of a given element:

<p style="font-family:'Vollkorn';">Lorem ipsum....</p>

I t doesn't get more painless than that.

The Simple JavaScript Method

Google also provides a simple JavaScript method for including custom fonts within a page.  This method requires including the JSAPI JavaScript file and a very small snippet of JavaScript:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
	google.load('webfont','1');
	google.setOnLoadCallback(function() {
		WebFont.load({
			google: {
				families: ['Tangerine','Cantarell']
			}
		});
	});
</script>

Selecting font variants is done with a simple ":" delimiter between the font and the variant:

WebFont.load({
	google: {
		families: ['Tangerine:bold']
	}
});

You may also load multiple fonts within the families array:

WebFont.load({
	google: {
		families: ['Tangerine:bold','Cantarell','Lobster']
	}
});

Simple, no?  If it's too simple for you, there's more advanced method.

The Advanced JavaScript Method

The advanced JavaScript method employes an async JavaScript method paired with a WebFontConfig object.  The advanced method also adds callbacks for font requests:

WebFontConfig = {
	google: {
		families: [ 'Tangerine', 'Cantarell' ]
	},
	/* Called when all the specified web-font provider modules (google, typekit, and/or custom) have reported that they have started loading fonts. */
	loading: function() {
		// do something
	},
	/* Called when each requested web font has started loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontloading: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called when each requested web font has finished loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontactive: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called if a requested web font failed to load. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontinactive: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called when all of the web fonts have either finished loading or failed to load, as long as at least one loaded successfully. */
	active: function() {
		// do something
	},
	/* Called if the browser does not support web fonts or if none of the fonts could be loaded. */
	inactive: function() {
		// do something
	}
};

/* async! */
(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);
})();

If you're like me, you loooooooove JavaScript callbacks.  You would use this method if you wanted to "preload" fonts before assigning fonts to specific elements. What's also great about this method is that Google uses "active" and "inactive" CSS class representations on the HTML element to designate what an element's settings should be before and after a font has been loaded:

.wf-inactive p { /* Show paragraphs in serif font until fonts have loaded. */
	font-family: serif
}
.wf-active p { /* Show paragraphs in Tangerine when the fonts have loaded. */
	font-family: 'Tangerine', serif
}
.wf-inactive h1 { /* Show heading in serif font until fonts have loaded. */
	font-family: serif;
	font-size: 16px
}
.wf-active h1 { /* Show heading in Cantarell when the fonts have loaded. */
	font-family: 'Cantarell', serif;
	font-size: 16px
}

Unfortunately you need to add these directives to you stylesheet; I prefer not to.

What do you think of Google latest JavaScript API?  On one side I see the Font API as extremely useful but the other side of me sees Google trying to grab a stronger hold of the Web;  trying to make websites dependent upon them.  What are your thoughts?

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?...

  • How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos

  • Create a Trailing Mouse Cursor Effect Using MooTools

    Remember the old days of DHTML and effects that were an achievement to create but had absolutely no value? Well, a trailing mouse cursor script is sorta like that. And I'm sorta the type of guy that creates effects just because I can....

  • CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

Discussion

  1. Nice review! I threw together a PHP lib that allows for similar functionality from one’s own server: http://bit.ly/bNA6Ej

  2. FontSquirrel.com is a great resource I’ve found for both open fonts and building you a nice chunk of @font-face code.

    On the other hand, are there any advantages to the JavaScript method? @font-face works well in IE6+, Firefox, and every other browser I’ve tested. Isn’t adding Javascript for something that can be accomplished with CSS a bad idea?

  3. Tried this couple of weeks ago, very simple to use, lets hope they add more fonts soon!

  4. @Brian Walker: I like that they provide callbacks with JavaScript. Beside that, I don’t see a giant advantage either.

  5. I don’t think that Google are ‘trying to make websites dependent upon them’. I think it’s something they want to use, so built, and so let everyone use.

    Because the cost of running it is surely negated by the good press that surrounds their pretty open approach to everything.

    I think it’s awesome.

  6. I don’t really see the point of it to be perfectly honest. @font-face CSS works like a charm and most of the Google Fonts seem to be regular open Fonts that you can find on FontSquirrel.

    Instead you have to rely on an external provider and Javascript… I mean I guess that I really shouldn’t argue against Google reliability but the latter however. As Brian already mentioned, doing something in JS that should be done in a stylesheet just seems like a bad idea.

  7. You can just use the CSS from Google if you don’t want to use the Javascript, it contains full file paths hosted on their servers so saves the hit on yours. If its anything like their JavaScript libs its on a CDN too so will be quick.

  8. I’ve found that some fonts from the Google Font API don’t display properly in Chrome or Internet Explorer, I show the solution here:

    http://webdesignandsuch.com/2010/07/fix-fonts-that-dont-work-with-google-font-api-in-internet-explorer-or-chrome-with-font-face/

  9. Using the Google Font API is now easier than ever with the new preview tool. See more here:

    http://tips4php.net/2010/07/google-font-api-new-preview-function/

  10. Evan

    Even with Google’s method there’s still a delay as the font downloads. This is the thing that keeps me from using embedded fonts.

  11. Hi David

    Thanks for this great blog.

    The Google font API rocks.

    Ive implemented it in a joomla template. The user can choose from 13 gogole fonts, in template parameters: Ive only choosen the readable fonts, because i didn’t know i could include more than one font. That would be great with 2 different fonts, for headlines and text :)

    I used the simple version:
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=params->get(“font”); ?>params->get(“fontStyle”); ?>”>

    Although the javascript version i alluring :D

    By using callback, you said that the font is preloaded! Does that mean than you won’t see the font change on load?

  12. David Spector

    These are all excellent comments. A pity that the author, in the Google tradition, chooses not to respond.

  13. Ya! Really Google API is great .It helps me in my project.Also one thing You Can download these fonts and use it offline for various purposes i.e. Typography

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...