Rey Bango

JavaScript, HTML, CSS & Random Stuff…

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.

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!

Contact Me

GMail: reybango at gmail dot com
Twitter: @reybango




JavaScript JS Documentation: JS Function Example: Specifying arguments with the Function constructor, JavaScript Function Example: Specifying arguments with the Function constructor

Twitter

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