What is the difference between a shim and a polyfill?
Shim
A piece of code that you could add (i.e. JavaScript) that would fix some functionality, but it would most often have it’s own API.Shims intercepts API calls and creates an abstract layer between the caller and the target. Typically shims are used for backward compability. For instance the es5-shim npm package will let you write ECMAScript 5 (ES5) syntax and not care if the browser is running ES5 or not. Take Date.now as an example. This is a new function in ES5 where the syntax in ES3 would be new Date().getTime(). If you use the es5-shim you can write Date.now and if the browser you’re running in supports ES5 it will just run. However, if the browser is running the ES3 engine es5-shim will intercept the call to Date.now and just return new Date().getTime() instead. This interception is called shimming. The relevant source code from es5-shim looks like this:

polyfill
something you could drop in (i.e. JavaScript) and it would silently work to mimic existing browser APIs that are otherwise unsupported.A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.A polyfill is a type of shim that retrofits legacy browsers with modern HTML5/CSS3 features usually using Javascript or Flash.Polyfill is about implementing missing features in an API, whereas a shim wouldn’t necessarily be as much about implementing missing features as it is about correcting features. As an example there is no support for sessionStorage in IE7, but the polyfill in the sessionstorage npm package will add this feature in IE7 (and older) by using techniques like storing data in the name property of the window or by using cookies.

Comments are closed.