Using Polyfills to Code with JavaScript

By Chris Minnick, Eva Holland

HTML5 brings some pretty amazing new functionality to JavaScript web pages, and the HTML 5 APIs are rapidly giving web browsers access to new universes of data and making installable computer applications a thing of the past. However, not every browser is on board with the future yet. Or, not every browser can agree on what that future should be.

As a result, it’s quite possible, and quite common to want to use a particular HTML tag or API and find that it just doesn’t work in some browsers. Fortunately, some ingenious folks have come up with a strategy, called polyfills, for implementing features in browsers that don’t yet support them.

Modernizr is a JavaScript library that detects whether a browser supports features of HTML5 and CSS3. A typical way to use a polyfill is to first detect whether the user’s browser supports the feature in question, using Modernizr, and then use the polyfill if not.

To install Modernizr, select the particular tests that you’ll be using in your web application, and build a custom version of the library that you can then import into your website using the script element.

Modernizr uses a simple syntax to select between different paths based on whether a user’s browser supports a feature. For example, here’s a Modernizr test that checks for geolocation support:

Modernizr.load({ 
 test: Modernizr.geolocation, 
 yep : 'geo.js', 
 nope: 'geo-polyfill.js'
});

A common case in which you would want to use a polyfill is with video. The HTML5 <video> element allows browsers to play videos without using any plugins. However, different browsers require different video formats, and some older browsers don’t support the <video> element at all.

In order to smooth over these differences, you can include and use a JavaScript polyfill called MediaElement.js. To use it, you can simply download and include the appropriate JavaScript and CSS files and include the following script elements in the <head> of your document:

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

Then, using just a single video file in any browser can be as simple as just using the <video> element and specifying a single .mp4 source file.

<video src="myvideo.mp4" width="320" height="240"></video>

If the browser doesn’t support <video> or this format, a Flash video player will be used as a backup.

Polyfills exist for nearly every new HTML5 feature. A complete list of polyfills is maintained by Modernizr.