10 of the best polyfills
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.
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.
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 you use Modernizr, it\’s likely that html5shiv is already included for you, so there\’s no need for you to include it again.
Definitely use it, if you\’re using HTML5 elements and your site gets any visits from old IE. It\’s a no-brainer.
Project URL: http://www.avto-pokraska.kiev.ua/
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.
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.
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.
Use if you\’re worried about the size of your CSS or are annoyed by writing prefixed properties.
Project URL: http://selectivizr.com/
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.
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.
Use on simple static pages, but stick with other traditional methods (e.g. simple classes) on large or highly dynamic pages.
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.
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.
Use Flexbox styles in your CSS (old syntax followed by new) and Flexie will find and render them automatically in IE:
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.
Use with caution, only if you really need Flexbox layout, and keep an eye on layout speed.
5. 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.
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.)
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.
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.
6. 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.
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
Also check out the unrelated JSON 3 project, which implements the same API with improved correctness and security, at the cost of speed.
Definitely use it if you need to work with JSON data in older browsers.
Project URL: https://github.com/kriskowal/es5-shim/
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.
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.
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.
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:
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:
After it\’s initialised, you can call canvas.getContext(\”2d\”) and access the rest of the canvas API like normal.
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.
Use with confidence, but have a degradation plan for users without the plug-in installed.
Project URL: http://mediaelementjs.com/
John Dyer\’s MediaElement.js works in two parts. Firstly it polyfills support for
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.
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):
Then, at the bottom of the body, initialise the player for any video or audio elements in the document:
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.
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.
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.
Download the latest distribution package and unpack it somewhere in your site structure. Include the following in the head of your page:
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:
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.
Use it if your site uses many of the supported features together.