Rey Bango

Web developer, honey badger

The Results of my Essential Tools, Libs and Frameworks for Front-End Development Survey

Two days ago, I put up a simple survey that asked what essential tools, libs and frameworks you were using for front-end development. I closed out the survey last night a little before 9pm EST and after getting 1000+ responses. I now want to share the results.

Why Am I Doing This?

As I’ve mentioned, this was an incredibly unscientific survey and not meant to determine which tool is best. Just which tools seem to be in heavy use.

I’m doing this to help web developers (myself included) stay on top of commonly used tools. Since change constantly but at least this gives a snapshot of what’s frequently used.

A couple of people buzzed me (some complaining and eluding bias), because I hadn’t listed “x” tool or lib in the survey. The survey wasn’t meant to be all-inclusive and if you look at the “Other” section below, you’ll see how adding everyone’s favorite tool would’ve been impossible. That’s what the “Other” option was for. Ultimately, instead of looking at what wasn’t there, you should read this for what was selected to determine if you need to get up-to-speed on specific tools.

The Process

After closing the survey, I removed all blank records and then went entry by entry to factor in the “Other” submissions and list out tools not originally added on the survey. I did my best to list every technology mentioned although it’s quite possible I may have missed something. If I did, it was purely accidental.

I ended up with 1031 total responses that I felt were good submissions. The results shown below for the main list was based off of what Google Docs provided. I didn’t do those calculations but I have to assume they’re correct.

Important to note is that the following options were added after 218 people had already replied so those values could’ve been much higher if added at the beginning. This is evident in Git & Coffeescript’s high numbers despite being added late.

  • LESS
  • Git
  • ExtJS
  • Ember.js
  • prefix-free
  • JSBin
  • JSFiddle
  • dabblet
  • Kendo UI
  • Wijmo
  • Coffeescript
  • YUI

Results from the Main List

Results from the “Other” Submissions

The ones listed below were submitted via the “Other” option and not on the main list.

A note about Enyo

EnyoJS is a framework released by HP which looks to have come out of the great work done by Palm. I haven’t used it and don’t have an opinion whether it’s actually awesome or not. I’ve held off on including it in these stats, though, because there was a high number of out-of-place submissions for it and they seemed clustered together around the same time. Additionally, MANY were single Enyo submissions with no other option chosen. Just seemed too odd to me but I’ll put out the data and if someone else wants to publish, go for it.

The Raw Data

Here’s the raw data from the survey. Please feel free to use it as you like and I hope it helps you out.

Raw Data from the Survey (.csv)

Essential Tools, Libs and Frameworks for Front-End Development. What are you Using?

UPDATE: The poll is now closed. You can see the results in this blog post.

I want to compile a list of the most common tools, frameworks & libs web developers are using today. Things seem to change daily with new, cool, and helpful projects announced all the time. It’d be great to nail some of these down as a reference.

Examples:

jQuery
Backbone
Underscore
Grunt
Mocha
RequireJS
HTML5 Boilerplate
Modernizr
SASS
Compass

Rebecca Murphey took a stab at this a couple of months ago.

So, what are you using that makes your front-end dev insanely easier?

iOS to IE10 Metro: Building Cross-Browser Plugin-Free Experiences

I’ve had the good fortune of working with my friend Jonathan Sampson recently on figuring out how to help developers build plugin-free experiences. With IE10 Metro going plugin-free, it’s incredibly important to document steps to help developers provide their users with great experiences without the need for proprietary 3rd party add-ons.

If you’ve built a plug-in-free browsing experience for the iPad, a few changes will make it ready for the new IE10 plug-in-free experience on Windows 8. As more browsers adopt the plug-in-free approach, now is a good time to start thinking about it. I’ll show you how to do this in a few steps below by writing code that works well in all modern browsers.

Today we’re going to work with a MSNBC plug-in-free experience for rich media. It breaks down to two things: styles and scripts.

To modify the files of MSNBC, I will be using a proxy application known as Fiddler. You can download this tool from http://fiddler2.com. This tool allows me to modify remote files as though they were on my local machine. If you have direct access to your own site, you can ignore Fiddler, and work directly with your files. Fiddler provides a great way for testing changes without the risk of breaking your live site.

Step 1: Declare Standards mode and valid markup for modern browsers

In order to use the HTML5 elements we’ll be utilizing below, you’ll first need to ensure that you are operating in standards mode. One way to ensure this is to include the HTML5 doctype at the top of your document:

<!DOCTYPE html>

Step 2: Update your CSS vendor prefixes

The CSS language is constantly in a state of change as new features are suggested, updated, and standardized. In order to allow developers to learn how to use these new features, browser vendors typically offer experimental implementations via prefixed properties.

A key part of using vendor prefixes responsibly is to ensure that prefixes from each vendor are included in your site to allow for the broadest level of feature support. In many cases, especially when building an iPad-centric site, you may have focused solely on -webkit properties, omitting the prefixes which target other browsers such as -o, -ms, and -moz. The end result of this is that you greatly limit the target devices that can render your plugin-free site to as well as provide a degraded experience for users of other modern browsers, many of which could serve up equally engaging functionality.

For instance, we find the following on MSNBC:

background: -webkit-gradient(
  linear,
  left top,
  left bottom,
  color-stop(1, rgba(192,192,192,.6)),
  color-stop(0.5, rgba(0,0,0,.6))
);

With the growing trend towards an HTML5 plugin-free experience, it’s important to expand these rules to provide the vendor prefixes of other major browsers as well.

background: -webkit-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -moz-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -ms-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -o-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: linear-gradient(
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );

While more verbose but the benefits to broad browser feature support certainly outweigh the extra typing involved. In addition, there are a number of great tools that can break down this workload, such as SASS and Compass, -prefix-free, or even CSS Snippets in the upcoming Visual Studio 2011.

Also, if you’re working predominantly in JavaScript and would like to save time determining which features are supported by your client’s browser, review the instructions in A Best Practice for Programming with Vendor Prefixes on the IEBlog.

Step 3: Get rid of browser sniffing methods

There are two methods used to determine what the user’s browser and device are capable of. One method, which unfortunately is somewhat popular, is browser sniffing. This method consists of examining the navigator object for certain patterns or values.

if ( navigator.userAgent.indexOf("iPad") > -1 ) {
  // Load HTML5 Experience
} else {
  // Load Flash Experience
}

The above code looks at the user agent string for the value “iPad”, and if found delivers a plug-in-free HTML5 experience. Otherwise, it’s assumed you are on a device that has Flash installed. This will result in a broken experience for non-iPad users who are browsing with plug-ins disabled, even though their browser is capable of handling HTML5 features.

Here is an attempt to find the version of Internet Explorer.

if ( tests.IE ) {
  j = /msie.(\d\.\d+)/i;
  k = navigator.userAgent.match(j)[1];
}

The user agent string is tested for a pattern that attempts to target the version number. This pattern looks for a single digit, followed by a period, followed by any number of additional digits. While this test will find values like “MSIE 8.0” and “MSIE 9.0”, it will not identify the latest version of Internet Explorer, which identifies itself as “MSIE 10.0”, since only one digit is expected before the period.

These are just a couple examples of why browser sniffing is not a best practice. The user agent string is not immutable – it is a read-write value that is easily changed by plugins, or even the user. Most modern browsers include the ability to easily change this value from their development tools, which some users take advantage of to get around poorly-developed websites.

If we disable plugins, or visit MSNBC from a device/browser that doesn’t have Flash, we would expect it to attempt a plug-in-free experience. Unfortunately, this is not the case. Rather than seeing an HTML5 experience, we’re instead asked to download Flash. This is because the site puts the user in one of two categories: an iPad user, or a Flash-enabled user.

Feature Detection

Rather than trying to guess what a browser is capable of by sniffing its user agent string (which will fail you eventually), it is much wiser to actually test features directly in the browser. If you wanted to test the browser’s ability to deliver video and audio via HTML5, you could actually attempt to create these elements via JavaScript, and see if the browser understands them. This practice is called feature detection.

if ( !!document.createElement(“video”).canPlayType  ) {
  // Load HTML5 Video
} else {
  // Load Flash Video
}

In the above example, we start by testing whether the canPlayType method exists on our newly-created video tag. We’re using double-negation to cast the response to a boolean. If the browser understands what a video element is, the canPlayType method will be present. If the video element is unknown to the browser, the canPlayType method will not exist. If this test passes, we load our HTML5 video. If the test does not pass, we attempt to load Flash. Deeper feature detection could take place here, since Flash may not be on the machine, or may be disabled.

Feature detection is the preferred method of determining what a browser is capable of, since there is no guesswork involved. If the browser passes properly-constructed tests, it absolutely supports the features you would like to use.

Many great tools exist to provide feature tests for you. Once such tool, which provides over 40 tests, is Modernizr. This tool creates a global object called “Modernizr” which contains the results of your tests. With Modernizr, testing for HTML5 video support is extremely easy:

if ( Modernizr.video ) {
  // Load HTML5 Video
}

MSNBC engages in browser sniffing to see if the device accessing the page is an iPad or not. Our first step is to remove the browser sniffing code, and replace it with feature detection code.

Before we can modify browser sniffing code, we first need to locate it. While in Internet Explorer, pressing F12 will pull up our Developer Tools. Within the tools, open the Script tab and do a search for “userAgent”. This search will seek out any instance of this property name in all of the site’s script files. We’re interested in the result from line 41 of http://www.msnbc.msn.com/id/37156949/.

Now that we know what we want to edit, we can open up Fiddler and load up our traffic. Once Fiddler is opened, perform a hard-refresh (Ctrl+F5 in IE) on the MSNBC page. This results in all of the page sessions being listed in Fiddler.

Looking carefully, you’ll notice our resource is the third from the top. Next I will setup an AutoResponder for this session file so that anytime it is requested, my own custom file is substituted in the place of the server response:

  1. Right-click this session and select “Decode Selected Sessions” from the context menu.
  2. Select the AutoResponder tab on the right.
  3. Click the “Enable automatic responses” checkbox in the AutoResponder tab.
  4. Drag the selected session from the left panel into the AutoResponder tab.

At this point, you should have an entry within your AutoResponder tab with the following rules:

  • If URI matches: EXACT:http://www.msnbc.msn.com/id/37156949/
  • Then respond with: *200-SESSION_3

Right-click the entry in the AutoResponder and select Edit Response. In the popup that follows, switch to the SyntaxView tab where we will find the source for this file. As expected, line 41 contains our browser sniffing code:

if(!(navigator.userAgent.toLowerCase().indexOf("ipad")>-1)){
  // Flash Experience
}

Rather than test the contents of the userAgent, we’re going to instead look for support for the HTML5 video tag. Switch the above condition to the following:

if ( !document.createElement("video").canPlayType ) {
  // Flash Experience
}

This test checks to see if we cannot use the video element. If canPlayType comes back as undefined, it will be cast to true and the first code block will be entered, setting up the Flash experience.

Step 4: Update touch and pointer events

Safari supports both a touch event model and a mouse event model. Internet Explorer 10 groups touch, mouse, and stylus events into a single abstract item known as a pointer. In fact, Internet Explorer 10 is the first browser to work for all input types, across all devices. This abstraction cuts down drastically on the amount of effort involved to determine which event model you ought to bind to and how to detect user-interaction. This pointer is then handled through MSPointer events. If necessary, you can determine the type of pointer by accessing the pointerType property.

Due to the fact Internet Explorer doesn’t support Apple’s proprietary event model, which includes touch events like touchstart, touchmove, and touchend, MSNBC’s event listeners will need to be amended to listen for MSPointer events like MSPointerDown, MSPointerUP, and MSPointerMove.

Due to the difference in event model implementations, use a feature detection tool like Modernizr or code like this to target all major event models:

if (window.navigator.msPointerEnabled) {
  myCanvas.addEventListener("MSPointerMove", paint, false);
} else {
  myCanvas.addEventListener("mousemove", paint, false);
  myCanvas.addEventListener(“touchmove”, paint, false);
}

MSNBC only supports touch events, which we will need to change so that visitors who happen to be using a mouse can still interact with the page:

Our events are tied up in http://www.msnbc.msn.com/id/43662671/15:

document.addEventListener("touchstart", touchHandler, false);
document.addEventListener("touchmove", touchHandler, false);
document.addEventListener("touchend", touchHandler, false);

We’re going to update this to include the MSPointer events as well:

if (window.navigator.msPointerEnabled) {
  document.addEventListener("MSPointerDown", touchHandler, false);
  document.addEventListener("MSPointerMove", touchHandler, false);
  document.addEventListener("MSPointerUp", touchHandler, false);
} else {
  document.addEventListener("touchstart", touchHandler, false);
  document.addEventListener("touchmove", touchHandler, false);
  document.addEventListener("touchend", touchHandler, false);
  document.addEventListener("mousedown", touchHandler, false);
  document.addEventListener("mousemove", touchHandler, false);
  document.addEventListener("mouseup", touchHandler, false);
}

First we’re checking for the presence of pointers. Since the MSPointer covers the mouse, fingers, and pens, we don’t need anything else besides them. We fall back, if necessary, to provide both touch and mouse events.

Next we need to create cases for these event types in http://www.msnbc.com/id/44937131/. Currently, MSNBC starts with the following:

if ( event.type == "touchstart" ) {
  /* Start drag logic */
} else 
if ( event.type == "touchmove" ) {
  /* Drag logic */
} else 
if ( event.type == "touchend" ) {
  /* Complete drag logic */
}

We’ll modify this to listen for all of the registered event types:

if ( event.type.match( /(down|start)$/i ) ) {
  /* Start drag logic */
} else 
if ( event.type.match( /move$/i ) ) {
  /* Drag logic */
} else 
if ( event.type.match( /(up|end)$/i ) ) {
  /* Complete drag logic */
}

The above uses the match method and a series of regular expressions to determine which event was raised. If the event raised ends with a case-insensitive “down” or “start”, we begin our drag code. If the event ends with a case-insensitive “move”, we perform the actual drag logic itself. And lastly, if the event ends with a case-insensitive “up” or “end”, we end our dragging event. Note: other events may be caught here as well, like onresizeend and keyup. Be sure to consider this in your project.

The above is an implementation of Ted Johnson’s solution in Handling Multi-touch and Mouse Input in All Browsers.

The drag logic itself initially relies upon the event.targetTouches TouchList. This member does not exist in Internet Explorer. The drag logic attempts to gather the pageX and pageY properties from the first item in the TouchList, however in Internet Explorer these values are found directly on the event object.

var curX = event.targetTouches[0].pageX;

Using the logical OR operator, I instruct curX to hold the value of event.pageX as long as event.pageX is present on the event object. If this property is not found, look within the targetTouches list:

var curX = event.pageX || event.targetTouches[0].pageX;

If event.pageX is not found, we fall back to assigning the value of targetTouches[0].pageX to our variable.

Another important item to keep in mind is that this site initially responds to touchmove. When this event is raised while touching the playlist, the code attempts to reposition the playlist based upon your touch movement. There is no hovering when it comes to touch – you’re either touching, or you’re not.

Now that we have mouse events tied into this logic, we have introduced the possibility for hovering. So while touchmove is free to reposition our playlist when it is over the playlist, we don’t want to do the same for mousemove. In fact, we only want the mousemove event to reposition the playlist when the mouse button is pressed.

For further reading, and examples on how to target all browsers, see Handling Multi-touch and Mouse Input in All Browsers.

Testing both experiences

Recall our feature detection from earlier, how we first check to see if HTML5 video support is in the user’s browser. If it is, we give them HTML5. If it is not, we give them Flash. One easy way to test our work is to use a browser, or document mode, that doesn’t support HTML5 features. This is very easy to test with Internet Explorer:

  1. Press F12 to reveal the Developer Tools
  2. Change your Document Mode to Internet Explorer 7 Standards
  3. Refresh the page

If our feature detection condition was written properly, you should now be watching a Flash-based presentation. Switching your Document Mode back into Internet Explorer 9 Standards (or “Standards” if you’re using IE10), will return you to the HTML5 experience.

Get it Done!

Hopefully this post helps to define the types of changes that will allow your iOS site to work properly in IE10 Metro and other plugin-free environments. By including best practices such as feature detection and responsibly using vendor prefixes for great new features, you should be able to provide your users a great experience, regardless of which browser or device they’re using. To assist with testing in other plug-in-free environments, download Internet Explorer 10 (currently available only in the Windows 8 CP) and begin testing today!

Update: In the rush to get this post up, I realized that I forgot to thank and give credit to Jonathan Sampson for helping investigate and write about the great techniques mentioned above. He was a huge help in generating many of these great techniques. Thanks JS!

How Polyfills “fill in the gaps” to make HTML5 and CSS3 Usable Today

There’s been a lot of commotion over the last week since the W3C announced that HTML5 is not ready yet for deployment to websites. Some really smart people have weighed in on this topic and I agree with their thoughts. Last Thursday, I did a presentation on the new features of HTML5 and part of that was demonstrating how polyfills work to allow you to leverage these new features while still providing a good cross-browser experience.

What’s a Polyfill?

I really love Paul Irish’s definition since it sums it up perfectly:

polyfill: A shim that mimics a future API, providing fallback functionality to older browsers.

The basic premise is that most older browsers may not have all of the features of the HTML5 and CSS3 specifications and they need a helping hand to make them provide a good user experience. A great example of this are the new HTML5 semantic tags like <article>, <section>, <header> & <nav> which render fine in all major modern browsers like IE9 beta, Firefox, Chrome, Safari & Opera but lack support in popular browsers like IE6 through IE8.

So for my demo, I decided to create a simple page that showed a blog-like layout using these new tags while ensuring that they can still render correctly in IE8. Here’s the layout code I used.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Rey's Awesome HTML5 Blog</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width; initial-scale=1.0" />
     
    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
  
</head>
 
<body>
    
	<header>
        <h1>Rey's Awesome HTML5 Blog</h1>
	</header>

    <nav>
    	<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
    </nav>
    	
	<section>

        <header>
        <h1>Rey's Blog Posts</h1>
	    </header>

        <article>
            <header><h1>The In's & Out's of HTML5</h1></header>
		    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. Fusce vitae orci. </p>

            <footer>
                October 7, 2010 - comments( 0 )
            </footer>
        </article>

        <article>
            <header><h1>HTML5 Ate My Lunch</h1></header>
		    <p>Fusce vitae orci. Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. </p>
            <footer>
                October 5, 2010 - comments( 3 )
            </footer>
	    </article>		

	</section>
		
	<footer>
		<p>Copyright Rey Bango, 2010</p>
	</footer>

</body>
 </html>

I used a HTML5 reset style sheet because unfortunately, most browser don’t have an internal style sheet that sets the expected behavior for specific elements. For example, you would expect an <section> element to be block level but due to a lack of the internal browser style sheet, it renders inline.

Then, I added the styles I needed to get my page to look the way I wanted:

/* Global */
body { font-size: 16px; font-family: arial,helvetica,clean,sans-serif;  }
a { color : #33CC33; } 
a:hover { text-decoration: none; }

/* Header */
header h1 { font-size: 48px; }

nav { overflow: auto; margin-bottom: 25px; }
nav li {float:left; padding-right: 5px; }

/* Main Content Area */
section { width: 500px; font-size: 12px; }
section h1 { font-size: 16px; }

article { background: #CCCC99; margin-bottom: 10px; padding: 5px; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; }
article footer { text-align: right; margin-right:5px; } 
article h1 { font-size: 12px; }

and when I tested it in Firefox 3.6.10, it looked exactly like I expected:

but look what happened when I tried to bring up the page in IE8:

None of the stylings were available because IE8 doesn’t recognize the new HTML5 elements. Further, in order to get IE6-8 to recognize these elements, you explicitly have to create the DOM nodes for them using JavaScript. The exact reason is unclear but it may be some type of parser bug. The following code needs to be in the <head> section of your page in order for the elements to be created and recognized by IE6-8:

document.createElement("header");
document.createElement("nav");
document.createElement("section");
document.createElement("article");
document.createElement("footer");

It’s a little bothersome to do that but it’s not a massive bit of code at least.

Enter Modernizr

The code I just listed to create your HTML5 elements is certainly useful but work has already been done to handle that for us via the awesome Modernizr JavaScript library. Not only does it act as a polyfill, creating these new elements for us automatically, but it offers a ton of detection capabilities for features of both HTML5 & CSS3. This allows you to determine how you will offer fallback support when a feature isn’t available.

Including Modernizr.js is incredibly easy since it’s only a one line script tag like this:

<script src="js/modernizr-1.5.min.js"></script>

As I mentioned, Modernizr is smart enough to determine when new semantic elements need to be created and will handle the dynamic creation of elements such as <article>, <section>, <header> & <nav> instead of you having to write JavaScript code to do it. So once I’ve added Modernizr to my page, I get the following results in IE8:

Now you’re probably looking at this screenshot and say, “Hey, you have no rounded corners!”. You’re right because I used the CSS3 border-radius property to create rounder corners for all of my <article> elements and IE8 doesn’t support that property. The important thing, though, is that IE8 now recognizes these new elements and allowed me to style them.

But What About those Rounder Corners?

Geez, you guys are so demanding! Okay, so the cool thing is that Modernizr offers detection of key features of HTML5 *and* CSS3 and with that, we can determine if something like border-radius is available and if not, using a new term coined by Alex Sexton, we’ll use “regressive enhancement” to provide similar capabilities for older browsers. In this case, we’re going to see if border-radius is available and if not, lazyload in Mike Aslup’s jQuery Corners plugin to fill in the gap:

    <!-- Load jQuery -->
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        // See if border-radius is available 
        if (!Modernizr.borderradius) {

            // If not, then load in the jQuery Corners plugin and apply rounded corners to the article elements
            $.getScript("js/jquery.corner.js", function () {
                $("article").corner();
            });

        }
    </script>

Now, when the code detects that border-radius is not available, it will just use the Corners jQuery plugin instead and render the following in any browser that doesn’t support the property:

Download the Code

I hope this post has shown you how polyfills can allow you to use HTML5 & CSS3 today. While I respect the W3C’s desire to ensure that the HTML5 specification is up-to-snuff, I think it’s important to realize that developers are resourceful and professional enough to create best practices that allow us to build apps with these new features right now.

I would highly recommend reviewing this VERY BIG LIST of polyfills and shims which can provide much of the missing capabilities in older browsers.

If you’d like to play with the code directly, I’ve packaged it up in a .zip file and you can download it here:

Code for HTML5 Semantic Tags using Polyfill to Degrade Gracefully (.zip)

Using @font-face and Font Squirrel to Enhance Your Site with Fonts

I’ve been dying to check out @font-face and so I popped over to Font Squirrel to see what they offered. Originally, I thought it was going to be a paid service but the cool thing is that they offer 100% “free for commercial use” fonts! They even have some nice font kits already setup. The reason that the kits are great is because depending on the browser you’re using, you may need a different font format for the browser to render the font correctly. See, even though @font-face is being hyped up now in CSS3, it’s more of a standardization effort and not really a new feature. In fact, @font-face is supported in IE6. Seriously.

The basic premise is that you define the available fonts beforehand in your css file by declaring an @font-face rule. For example, I downloaded a font called “Arch Rival” and grabbed the whole kit because it included the font formats for every major browser as well as iPhone & iPad and I wanted to make sure they rendered correctly.

Typically, you would manually go into your CSS style sheet and enter a @font-face rule like this:

@font-face {
	font-family: 'SFArchRivalRegular';
	src: local('☺'), url('SF_Arch_Rival-webfont.eot');
	font-weight: normal;
	font-style: normal;
}

where src is the path to your physical font file. So yes, you can specify relative pathing for your font file like this:

src: url('fonts/SF_Arch_Rival-webfont.eot');

Once defined, you can now use the font’s semantic name to style a specific selector like this:

.post {
   font-family: 'SFArchRivalRegular';
   font-size: 18px;
}

This is fairly easy for a one-off type of deal but when you’re dealing with font that could have various rendering formats such as bold, italics, bold italics, extended italics, etc., entering all of this can become really tedious. If you don’t believe me, just check out the following style sheet. Font Squirrel takes the pain out of this.

When you download a font kit, you have a choice of downloading one big bundle with all of the necessary formats or using a font builder that allows you to select which format you’d like to use:

In my case, I chose everything and the really great thing is that the kit brought a pre-made CSS style sheet with all of the font definitions as well as a demo HTML file which included declarations that referenced the new font! This made it incredibly easy to get up and running quickly. If we look at the CSS style sheet declaration, we can see that the src property declares a number of additional formats for the Arch Rival font including the format() hint to define the format type:

@font-face {
	font-family: 'SFArchRivalRegular';
	src: url('SF_Arch_Rival-webfont.eot');
	src: local('☺'), url('SF_Arch_Rival-webfont.woff') format('woff'), url('SF_Arch_Rival-webfont.ttf') format('truetype'), url('SF_Arch_Rival-webfont.svg#webfontPgLtCzUx') format('svg');
	font-weight: normal;
	font-style: normal;
}

If we look at the demo page, we can see how the various font declarations affect the page.

So I decided to play a little more with some other fonts and pulled down a kit called “True Crimes“. I copied the font files into their own directory, updated the included style sheet to point to the right directory and then included the code into my blog.

@font-face {
font-family: ‘TrueCrimesRegular’;
src: url(‘/fonts/true-crimes-webfont.eot’);
src: local(‘☺’), url(‘/fonts/true-crimes-webfont.woff’) format(‘woff’), url(‘/fonts/true-crimes-webfont.ttf’) format(‘truetype’), url(‘/fonts/true-crimes-webfont.svg#webfontWTZyAk71′) format(‘svg’);
font-weight: normal;
font-style: normal;
}
h2.fontdemo {font: 60px/68px ‘TrueCrimesRegular’, Arial, sans-serif;letter-spacing: 0; }
[/code]

If you're curious about the multiple src property declarations, it has to do with IE and its support of the Embedded OpenType (.eot) font format, which no other browser supports. The declaration order ensures that IE will be able to find the right font file without falling over itself. Paul Irish has a nice explanation of the issue so be sure to read it.

Now, I can have a little fun whenever I want to by simply declaring an H2 header tag with a class of "fontdemo" and some text like this:

<h2 class="fontdemo">I'm digging @font-face!!</h2>

which gets me this:

I'm digging @font-face!!

A Bit of a Warning

Keep in mind that when you use @font-face in your site, you're now adding another HTTP request which could end up slowing down your page load. This is especially important to consider if you decide to use a remote font hosting service. Be sure to read Steve's thorough analysis of @font-face performance before going hog wild on your site. :)

An Update

Paul Irish pointed out the I had left out the local('☺') directive from the @font-face rule, which is really important in terms of performance since, as Paul wrote:

if it just so happens that a user actually has your custom font installed, this'll save them the download. The primary reason is that you cede control to the user's machine, potentially showing a locally installed font instead of the one you want to serve. While that will load faster, there's a very small chance the file could be wrong.

To account for this gotcha, I've specified a local font name of '☺'. Yes, it's a smiley face. The OpenType spec indicates any two-byte unicode characters won't work in a font name on Mac at all, so that lessens the likelihood that someone actually released a font with such a name. This technique is recommended if you think a locally installed version of this font is not in your best interest.

Also, because the local('☺') directive isn't supported it IE, it will simply ignore the second src declaration (which is for non-IE browsers) ensuring that you don't have an extra request that will issue a 404 and slow down your page's performance.

Thanks Paul!

Start Using CSS3 Pseudo-Classes in Internet Explorer 6, 7, and 8 using the Selectivizr JavaScript Library

Now that everyone is all giddy about CSS3 and all of the coolness it offers, lets get back down to earth. We still have older browsers to support so while using some of the new nifty features is definitely cool, we need to ensure we understand that at least 80% of web users won’t be on a cool new browser.

Enter Selectivizr, the Library Formerly Known as ie-css3.js

Internet Explorer is definitely one of those that needs special attention which is where a new library called Selectivizr comes in. It’s a JavaScript library that allows you to take advantage of CSS3 selectors now, even for users of Internet Explorer 6 through 8, by emulating these pseudo-selectors via JavaScript. It’s become such a hit that it was even nominated for Innovation of the Year in .net magazine’s 2010 awards.

The inclusion of Selectivizr is extremely easy. You add it in using a standard script tag just like any other JavaScript file. Notice that we’re using IE conditional statements to determine the browser version and if it’s less than IE9, the library gets included. Makes sense since IE9 should include many of these pseudo-selectors.

<script src="jquery-1.4.2.min.js"></script>
<!--[if lt IE 9]>
	<script src="selectivizr.js"></script>
	<noscript><link rel="stylesheet" href="css/ie-fallback.css" media="screen, projection"></noscript>
<![endif]--> 	
<link href="style.css" rel="stylesheet"> 

Once included, you’re now free to add CSS3 pseudo-classes to your style sheet. For example, I can now use the nth-child() pseudo-class to set the text to every odd numbered paragraph within my container div to red:

#container p:nth-child(odd) { color: #ff0000; }

and it will render correctly in Internet Explorer versions 6-8.

Check it out in Internet Explorer with Selectivizr NOT included.
Check it out in Internet Explorer with Selectivizr included.

In order to have done this previously, I would’ve have to had to rely on complex JavaScript or using methods included in a JavaScript library (e.g. jQuery’s nth-child method) to be able to grab the DOM element and style it. For example:

        $(document).ready(function () {

            $("#container p:nth-child(odd)").css("color", "#ff0000");

        });

Check out the jQuery version in Internet Explorer with Selectivizr NOT included.

While that will style the paragraphs the way I want, it’s not a portable and reusable solution. Using Selectivizr is substantially easier because I can now specify reusable CSS rules where they belong; in a style sheet.

The main thing that you NEED to have is a JavaScript library with a DOM selector engine. Selectivizr has support for jQuery, MooTools, Dojo, Prototype, YUI, DOMAssistant and the NWMatcher selector engine. Considering that most sites leverage at least one of these libs, that’s pretty good coverage.

One of the things I did notice when doing a view source on the Selectivizr website is something that I had already thought would be a good idea. The author, Keith Clark, combines his Selectivizr code with Remy Sharp’s html5shiv which makes a lot of sense considering html5shiv allows you style HTML5 tags in non-supporting browsers. So rolling up these two libs (or Modernizr) is a good idea. One less http request to make.

How Does this Work?

I pinged Keith so I can get a better understanding of the magic going on under the hood and here’s what he said:

Basically, the script scans the page looking for <link>‘d style sheets which are downloaded using a XmlHttpRequest (or ActiveX for IE6). The style sheets are then parsed for rules containing CSS3 selectors. Any matching rules are extracted and passed to a JavaScript library (such as jQuery, Prototype, NWMatcher etc.) which selects matching elements from the page. These elements are then given a unique className and, if necessary, event handlers are added (if interactive pseudo-classes such as :hover, :focus, : checked etc. need to be emulated). The original CSS rule is then replaced with the same className and once all rules are processed, the original style sheet content is replaced with the modified one.

So if you’re wondering why there’s a dependency on a JS lib, there ya go. For a deeper dive into the how-to’s check out his more thorough explanation here.

Sponsors



Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Categories

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache