Advanced Sass : online course

Dynamically import only used Google Webfonts

When designing in the browser you often try out multiple fonts and weights, and in the end you don't really remember which variations you're actually using. The result: imported webfonts that take up bandwidth and HTTP-requests, but aren't used. Sass to the rescue!

This is going to be a pretty advanced technique with some hardcore Sass coding. Don't worry: I'll go through things step by step. Because of the amount of code I suggest clicking the "Play with this gist" links underneath each code sample. It will open the code samples in a larger window. This article is very much about what the online Advanced Sass course will be about: not just how to write Sass that compiles, but apply that knowledge to creative problem solving.

For this example we're going to use both the "Open Sans" and "PT Serif" webfonts, as offered by Google Fonts. Combined they offer 14 styles and weights, and we'll use Sass to keep track of what's being used and dynamically construct an @import for us to fetch the fonts from Google. After setting things up, we'll substitute our font-family, font-weight and font-style properties with a mixin (using sensible defaults).

First, let's write a mixin that has defaults for weight and style, and have it output some CSS:

Play with this gist on SassMeister.

Time to spice things up: we're adding a variable in the global namespace that contains a map of all fonts and variations used. When including the font mixin, we first check if this combination already exists in the map. If not, we add it to it. For these last bits I'm using a separate mixin: I like to have these sort of "utility tasks" performed separately, so I can reuse them (again, please view in a larger window):

Play with this gist on SassMeister.

Now our font map looks like this:

In the last step we're adding our final mixin. This one will take the contents of the $used-fonts variable, loop through it and come up with a Google URL we can @import. It's included at the very bottom, after all used fonts have been processed (Sass conveniently moves it to the top of the compiled CSS though).

Play with this gist on SassMeister.

We now have dynamically created this @import: url(http://fonts.googleapis.com/css?family=Open+Sans:400,700,600italic|PT+Serif:400);

That's it: no more unneeded and unwanted Google Fonts in our CSS and over the wire! Drop a line in the comments if this blew your mind ;-)

The above is part of the Advanced Sass online course, which helps you turn your Sass up to eleven. You can become a Sass expert too!