HTML5How to

10 of the best polyfills

10 of the best polyfills

Use modern HTML5 features without breaking your design in older browsers.

Advertisement

Shims that mimic standard HTML5 features and APIs, commonly referred to as polyfills, are becoming more and more common as developers strive to push the web forward. The Modernizr community maintains an exhaustive list of known polyfills, containing hundreds of projects of varying completeness and quality. Here are 10 recommended polyfills that are among the best and most widely used today.

01. html5shiv

Project URL: https://github.com/aFarkas/html5shiv

In IE versions prior to 9, unknown HTML elements like <section> and <nav> would be parsed as empty elements, breaking the page's nesting structure and making those elements unstyleable. One of the most widely-used polyfills, html5shiv exploits another quirk of IE to work around this bug: calling document.createElement("tagname") for each of the new HTML5 elements, which magically makes IE parse them correctly. It also includes basic default styling for those HTML5 elements.

Usage

Download the html5shiv.js file (or html5shiv-printshiv.js if you need printing support) from the project's dist directory and put it somewhere in your site files. Reference the script file from within the <head> of your document after any stylesheets to optimise performance. Make sure you wrap it in conditional comments so it's only downloaded by the older IE versions that need it.

<!--[if lt IE 9]>
<script src="path/to/html5shiv.js"></script>
<![endif]-->

Notes

If you use Modernizr, it's likely that html5shiv is already included for you, so there's no need for you to include it again.

Recommendation

Definitely use it, if you're using HTML5 elements and your site gets any visits from old IE. It's a no-brainer.

02. -prefix-free

Project URL: http://leaverou.github.com/prefixfree/

Though most polyfills target out-of-date browsers, some exist to simply push modern browsers forward a little bit more. Lea Verou's -prefix-free polyfill is such a polyfill, allowing current browsers to recognise the unprefixed versions of several CSS3 properties instead of requiring you to write out all the vendor prefixes. It reads your page's stylesheets and replaces any unprefixed properties with their prefixed counterparts recognised by the current browser.

Usage

Download prefixfree.min.js from the project homepage into your site directory. Include it in your page's <head> immediately after all of your stylesheets.

<link rel="stylesheet" href="/css/styles.css">
<script src="/path/to/prefixfree.min.js"></script>

Notes

The biggest limitations are described on the project's homepage. As always, measure the perceived load time of your page with the polyfill in place, to make sure that the time it spends loading and rewriting the CSS client-side isn't causing a noticeable delay.

A CSS preprocessor like Sass may also be a good alternative, though that still requires sending all the prefixed CSS over the network. Weigh the size of the preprocessed CSS against the size of the -prefix-free polyfill plus its processing time.

Recommendation:

Use if you're worried about the size of your CSS or are annoyed by writing prefixed properties.

03. Selectivizr

Project URL: http://selectivizr.com/

Keith Clark's Selectivizr is a popular polyfill for making many CSS3 selectors work in IE 8 and below. It reads the page's stylesheets looking for a number of known CSS3 selectors, then uses a JavaScript selector library to query the document for elements matching those selectors, applying the styles directly to those elements. It supports several JavaScript selector libraries, one of which you're probably already using in your page.

Usage

Download the distribution package and unzip it somewhere in your site directory. Reference selectivizr-min.js in the <head> of your page, after a reference to the JS selector library of your choice (jQuery in the example code below). Wrap it in a conditional comment so only old IEs download it, and optionally use a <noscript> to include fallback styling.

<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<!--[if (gte IE 6)&(lte IE 8)]>
  <script type="text/javascript" src="/path/to/selectivizr-min.js"></script>
  <noscript><link rel="stylesheet" href="/path/to/fallback-styles.css" /></noscript>
<![endif]-->

Notes

The main caveats are described at the bottom of selectivizr.com, the most important being that the query is run once on page load and does not automatically handle dynamic additions to the DOM, which hampers its use on dynamic sites.

Recommendation

Use on simple static pages, but stick with other traditional methods (e.g. simple classes) on large or highly dynamic pages.

04. Flexie

Project URL: http://flexiejs.com/

Possibly one of the most anticipated features of CSS3, Flexible Box Layout (a.k.a. Flexbox) promises to be an extremely powerful tool for laying out interface elements. WebKit and Mozilla engines have supported a preliminary draft syntax for years. Flexie implements support for that same syntax in IE and Opera.

However, keep in mind that the draft spec has undergone a drastic revision to a new (and much more powerful!) syntax, which is not yet supported by Flexie. You can still use Flexie along with the old syntax, but make sure you include the new syntax for future browsers as well.

Usage

Download Flexie to your site and reference flexie.min.js in your page after the stylesheets, along with your choice of JS selector engine like jQuery.

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/flexie.min.js"></script>

Use Flexbox styles in your CSS (old syntax followed by new) and Flexie will find and render them automatically in IE:

.toolbar {
    /* old syntax: */
    display: -webkit-box;
    display: -moz-box;
    display: box;
    -webkit-box-orient: horizontal;
    -moz-box-orient: horizontal;
    box-orient: horizontal;

    /* new syntax: */
    display: flex;
    flex-direction: row;
}

.toolbar > .message {
    /* old syntax: */
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;

    /* new syntax: */
    flex: 1;
}

Notes

Besides the syntax issue, make sure to read the requirements and caveats in the project Readme for common issues. Flexie uses the base engine from Selectivizr, so the same limitations also apply.

Recommendation

Use with caution, only if you really need Flexbox layout, and keep an eye on layout speed.

05. CSS3 PIE

Project URL: http://css3pie.com

PIE (“Progressive Internet Explorer”) implements some of the most popular missing CSS3 box decoration properties in IE, including border-radius and box-shadow for IE 8 and below, and linear-gradient backgrounds for IE 9 and below. Invoked as a HTC behavior (a proprietary IE feature), it looks for the unsupported CSS3 properties on specific elements and renders those properties using VML for IE 6-8 and SVG for IE 9. Its rendering is mostly indistinguishable from native browser implementations and it handles dynamic DOM modification well.

Usage

Download the distribution package and unzip it somewhere in your site directory. In your CSS, for each rule containing CSS3 properties, add a behavior property pointing to PIE.htc (note that the base for relative paths is the page URL, not the CSS file like you'd normally expect.)

.box {
    border-radius: 8px 8px 0 0;
    box-shadow: #666 0px 2px 3px;
    behavior: url(/path/to/PIE.htc);
}

Notes

Most of the commonly encountered issues are documented on the site. HTC behaviors can be a bit tricky to work with at times, so there is also a standalone PIE.js version that can be used as a more manual alternative.

The rendering process is intensive, and PIE favours accuracy over speed, so watch that you're not using it on too many elements to prevent noticeable lag on page load.

Recommendation

Use sparingly, and only if you really have to. Decoration styles are usually not critical to a site's functionality, so graceful degradation is usually preferable.

06. JSON 2

Project URL: https://github.com/douglascrockford/JSON-js

Douglas Crockford originally wrote json2.js as an API for reading and writing his up-and-coming JSON data format. It became so widely used that the browser makers decided to implement its API natively and turn it into a “de facto” standard; json2.js was transformed from a library to a polyfill after the fact.

Usage

Download json2.js to your site directory, and reference it in a script element. To prevent it from being downloaded by browsers that support JSON natively, you can dynamically include it based on a check for the global JSON object:

<script>
if (!window.JSON) {
  document.write('<script src="path/to/json2.js"><\/script>');
}
</script>

Notes

Also check out the unrelated JSON 3 project, which implements the same API with improved correctness and security, at the cost of speed.

Recommendation

Definitely use it if you need to work with JSON data in older browsers.

07. es5-shim

Project URL: https://github.com/kriskowal/es5-shim/

ECMAScript 5th Edition (“ES5”) brings some handy new scripting features, and since they're syntactically compatible with older JavaScript engines they can mostly be polyfilled by patching methods onto built-in JS objects. This es5-shim polyfill does it in two parts: es5-shim.js containing those methods that can be fully polyfilled, and es5-sham.js containing partial implementations of the other methods which rely too much on the underlying engine to work accurately.

Usage

Download es5-shim.min.js (and/or es5-sham.min.js) from the project repository into your site directory. Include it in your page, before any other scripts that use the ES5 features.

<script src="/path/to/es5-shim.min.js"></script>

Notes

If you only need a few of the ES5 methods, the es5-shim.js source code is well documented so you can easily remove the ones you don't need and trim down the file size.

For the very brave, es6-shim does the same for the basic parts of ECMAScript 6. ES6 has fewer syntactically compatible features, however, and very few browsers support it natively yet, so its benefit is minimal at this point.

Recommendation

Definitely use it if your JavaScript code can benefit from the ES5 methods, so that modern browsers can use the speedy native implementations.

08. FlashCanvas

Project URL: http://flashcanvas.net/

FlashCanvas is exactly what its name suggests: an implementation of the HTML5 Canvas API using a Flash plug-in. A rare commercial polyfill, it comes in a paid 'pro' version, as well as a free version, which just lacks a few advanced features like shadows.

Usage

Download the distribution you want to use and unzip it somewhere in your site directory. Reference flashcanvas.js from the <head> of your page, enclosed in a conditional comment:

<!--[if lt IE 9]>
<script src="/path/to/flashcanvas.js"></script>
<![endif]-->

This automatically replaces each <canvas> element in the page's initial markup with an instance of the .swf plug-in. If you dynamically add a canvas to the page later on, you'll have to manually initialise it:

FlashCanvas.initElement(newCanvasElement);

After it's initialised, you can call canvas.getContext("2d") and access the rest of the canvas API like normal.

Notes

Besides the obvious limitation of requiring your users to have the Flash plug-in installed, FlashCanvas's rendering is highly spec-compliant and speedy. If requiring a plug-in is a deal breaker for you, ExplorerCanvas (a.k.a. Excanvas) is another option, which renders using VML, but it is far less complete and much slower so it's not generally recommended.

Recommendation

Use with confidence, but have a degradation plan for users without the plug-in installed.

09. MediaElement.js

Project URL: http://mediaelementjs.com/

John Dyer's MediaElement.js works in two parts. Firstly it polyfills support for <video> and <audio> elements, including the HTML5 MediaElement API, in older browsers using Flash or Silverlight plug-ins. It also provides an attractive media player UI for those elements, which is consistent across all browsers, if you wish to use it.

Usage

Download the latest distribution from the project homepage and unpack it into your site structure. Include the stylesheet and script in the <head> of your page, along with the jQuery dependency (Zepto will also work):

<link rel="stylesheet" href="/path/to/mediaelementplayer.min.css">
<script src="/path/to/jquery.js"></script>
<script src="/path/to/mediaelement-and-player.min.js"></script>

Then, at the bottom of the <body>, initialise the player for any <video> or <audio> elements in the document:

<script>
  $('video,audio').mediaelementplayer();
</script>

See the documentation for options you can pass to the player creation method, as well as instructions on using the standalone MediaElement constructor to polyfill the API without the player UI.

Notes

As always, inconsistent video and audio codec support between browsers is a tricky issue. MediaElement.js can help you out there too, by triggering the Flash/Silverlight player as a fallback in browsers that support the HTML5 media elements but not the right codec. Check out the matrix of codec support on its homepage for details.

Recommendation

Highly recommended, if not for the polyfilled API then for its excellent customisable player UI.

10. Webshims Lib

Project URL: http://afarkas.github.com/webshim/demos/

Rather than polyfilling any features itself, Alexander Farkas's Webshims Lib aggregates a bunch of other polyfills together into a single package and conditionally loads only those needed by the visiting browser.

Usage

Download the latest distribution package and unpack it somewhere in your site structure. Include the following in the <head> of your page:

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/js-webshim/minified/extras/modernizr-custom.js"></script>
<script src="/path/to/js-webshim/minified/polyfiller.js"></script>

<script>
    // Load all supported polyfills, if the browser needs them:
    $.webshims.polyfill();
</script>

You can use a custom Modernizr build instead of the one provided if you wish. Also you can alternatively specify a list of desired features to skip unnecessary feature detection:

<script>
    // Load only these polyfills, if the browser needs them:
    $.webshims.polyfill("canvas mediaelement");
</script>

Notes

Its dependence on jQuery and Modernizr, plus the not-so-tiny polyfiller.js itself, make it a bit heavyweight. If you only use a few of the supported features, conditionally including those polyfills individually yourself could result in a smaller overall file size.

Recommendation

Use it if your site uses many of the supported features together.

Jason Johnston www.css3pie.com is a web software engineer at Sencha and the creator of the CSS3 PIE polyfill. A classically trained musician with a degree in piano performance, he approaches writing software like he approaches music: a dynamic blend of art and science, requiring constant practice, where there is always room for further refinement and creativity.

 

Advert

Log in to Creative Bloq with your preferred social network to comment

OR

Log in with your Creative Bloq account

site stat collection