Treehouse

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?

ydkjs-2.png

Recent Features

  • 6 Things You Didn&#8217;t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving,...

  • CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • MooTools Flashlight Effect

    Another reason that I love Twitter so much is that I'm able to check out what fellow developers think is interesting. Chris Coyier posted about a flashlight effect he found built with jQuery. While I agree with Chris that it's a little corny, it...

  • Comment Preview Using MooTools

    Comment previewing is an awesome addition to any blog. I've seen really simple comment previewing and some really complex comment previewing. The following is a tutorial on creating very basic comment previewing using MooTools. The XHTML You can set up your XHTML any way you'd like....

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!