Polyfill (programming)

Last updated

In software development, a polyfill is code that implements a new standard feature of a deployment environment within an old version of that environment that does not natively support the feature. Most often, it refers to JavaScript code that implements an HTML5 or CSS web standard, either an established standard (supported by some browsers) on older browsers, or a proposed standard (not supported by any browsers) on existing browsers. Polyfills are also used in PHP and Python. [1]

Contents

Polyfills allow web developers to use an API regardless of whether or not it is supported by a browser, and usually with minimal overhead. Typically they first check if a browser supports an API, and use it if available, otherwise using their own implementation. [2] [3] Polyfills themselves use other, more supported features, and thus different polyfills may be needed for different browsers. The term is also used as a verb: polyfilling is providing a polyfill for a feature.

Definition

The term is a neologism, coined by Remy Sharp, who required a word that meant "replicate an API using JavaScript (or Flash or whatever) if the browser doesn’t have it natively" while co-writing the book Introducing HTML5 in 2009. [4] [5] Formally, "a shim is a library that brings a new API to an older environment, using only the means of that environment." [2] Polyfills exactly fit this definition; the term shim was also used for early polyfills. [6] However, to Sharp shim connoted non-transparent APIs and workarounds, such as spacer GIFs for layout, sometimes known as shim.gif, and similar terms such as progressive enhancement and graceful degradation were not appropriate, so he invented a new term. [5] The term is based on the multipurpose filling paste brand Polyfilla, a paste used to cover up cracks and holes in walls, and the meaning "fill in holes (in functionality) in many (poly-) ways." The word has since gained popularity, particularly due to its use by Paul Irish and in Modernizr documentation. [5] [7]

The distinction that Sharp makes is: [4]

What makes a polyfill different from the techniques we have already, like a shim, is this: if you removed the polyfill script, your code would continue to work, without any changes required in spite of the polyfill being removed.

This distinction is not drawn by other authors. [2] At times various other distinctions are drawn between shims, polyfills, and fallbacks, but there are no generally accepted distinctions: most consider polyfills a form of shim. [8] The term polyfiller is also occasionally found. [9]

Examples

core-js

core-js [10] is one of the most popular [11] JavaScript standard library polyfills. Includes polyfills for ECMAScript up to the latest version of the standard: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution. It can be integrated with Babel, which allows it to automatically inject required core-js modules into your code.

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 impossible to style using CSS. One of the most widely used polyfills, html5shiv, [lower-alpha 1] exploits another quirk of IE to work around this bug: calling document.createElement("tagname") for each of the new HTML5 elements, which causes IE to parse them correctly. It also includes basic default styling for those HTML5 elements.

-prefix-free

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 the developer to write out all the vendor prefixes. It reads the page's stylesheets and replaces any unprefixed properties with their prefixed counterparts recognised by the current browser.

Selectivizr

Keith Clark's Selectivizr is a popular polyfill that makes 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 such as jQuery.

Flexie

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, the draft spec has undergone a drastic revision to a new (and much more powerful) syntax, which is not yet supported by Flexie. Flexie can still be used along with the old syntax, but the developer must make sure they include the new syntax for future browsers as well.

CSS3 PIE

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.

JSON 2

Douglas Crockford originally wrote json2.js as an API for reading and writing his (then up-and-coming) JSON data format. It became so widely used that browser vendors decided to implement its API natively and turn it into a de facto standard; Since json2.js now implements features native to newer browsers into older browsers, it has become a polyfill instead of a library.

es5-shim

ECMAScript 5th Edition ("ES5") brings some useful 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 contains those methods that can be fully polyfilled, and es5-sham.js contains partial implementations of the other methods which rely too much on the underlying engine to work accurately.

FlashCanvas

FlashCanvas is an implementation of the HTML5 Canvas API using an Adobe Flash plug-in. A rare commercial polyfill, it comes in a paid version, as well as a free version, which lacks a few advanced features like shadows.

MediaElement.js

John Dyer's MediaElement.js 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 optional media player UI for those elements, which is consistent across all browsers.

Polyfill.io

A JavaScript library created by Andrew Betts that implemented Polyfill. In February 2024, the library's domain was acquired by China-based company Funnull and within a few months became part of a supply chain attack. [12] [13]

BrowserID

Authentication protocol proposed by Mozilla, failed to gain traction. [14]

Webshims Lib

Alexander Farkas's Webshims Lib aggregates many other polyfills together into a single package and conditionally loads only those needed by the visiting browser.

Hyphenopoly.js

Hyphenopoly.js enables automatic hyphenation if it is not already supported by the browser for the respective document language. [15]

See also

Notes

  1. The use of the term shiv here is a pun or mistake on shim. [4]

Related Research Articles

<span class="mw-page-title-main">JavaScript</span> High-level programming language

JavaScript, often abbreviated as JS, is a programming language and core technology of the Web, alongside HTML and CSS. 99% of websites use JavaScript on the client side for webpage behavior.

ECMAScript is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is standardized by Ecma International in the document ECMA-262.

JScript is Microsoft's legacy dialect of the ECMAScript standard that is used in Microsoft's Internet Explorer web browser.

A CSS hack is a coding technique used to hide or show CSS markup depending on the browser, version number, or capabilities. Browsers have different interpretations of CSS behavior and different levels of support for the W3C standards. CSS hacks are sometimes used to achieve consistent layout appearance in multiple browsers that do not have compatible rendering. Most of these hacks do not work in modern versions of the browsers, and other techniques, such as feature support detection, have become more prevalent.

<span class="mw-page-title-main">YUI Library</span>

The Yahoo! User Interface Library (YUI) is a discontinued open-source JavaScript library for building richly interactive web applications using techniques such as Ajax, DHTML, and DOM scripting. YUI includes several cores CSS resources. It is available under a BSD License. Development on YUI began in 2005 and Yahoo! properties such as My Yahoo! and the Yahoo! front page began using YUI in the summer of that year. YUI was released for public use in February 2006. It was actively developed by a core team of Yahoo! engineers.

jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animations, and Ajax. It is free, open-source software using the permissive MIT License. As of August 2022, jQuery is used by 77% of the 10 million most popular websites. Web analysis indicates that it is the most widely deployed JavaScript library by a large margin, having at least three to four times more usage than any other JavaScript library.

<span class="mw-page-title-main">Internet Explorer 9</span> Web browser for Windows released in 2011

Internet Explorer 9 or IE9 is the ninth major version of the Internet Explorer web browser for Windows. It was released by Microsoft on March 14, 2011, as the successor to Internet Explorer 8. Microsoft released Internet Explorer 9 as a major out-of-band version that was not tied to the release schedule of any particular version of Windows, unlike previous versions. It is the first version of Internet Explorer not to be bundled with a Windows operating system, although some OEMs have installed it with Windows on their PCs. Internet Explorer 9 was the last version to be called Windows Internet Explorer. The software was rebranded simply as Internet Explorer starting with the release of Internet Explorer 10.

<span class="mw-page-title-main">Sass (style sheet language)</span> Stylesheet language

Sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). SassScript is the scripting language itself.

<span class="mw-page-title-main">WebGL</span> JavaScript bindings for OpenGL in web browsers

WebGL is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing GPU-accelerated usage of physics, image processing, and effects in the HTML canvas. WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

<span class="mw-page-title-main">Google Closure Tools</span> JavaScript developer toolkit

Google Closure Tools is a set of tools to help developers build rich web applications with JavaScript. It was developed by Google for use in their web applications such as Gmail, Google Docs and Google Maps. As of 2023, the project had over 230K LOCs not counting the embedded Mozilla Rhino compiler.

A browser speed test is a computer benchmark that scores the performance of a web browser, by measuring the browser's efficiency in completing a predefined list of tasks. In general the testing software is available online, located on a website, where different algorithms are loaded and performed in the browser client. Typical test tasks are rendering and animation, DOM transformations, string operations, mathematical calculations, sorting algorithms, graphic performance tests and memory instructions. Browser speed tests have been used during browser wars to prove superiority of specific web browsers. The popular Acid3 test is no particular speed test but checks browser conformity to web standards.

Modernizr is a JavaScript library that detects the features available in a user's browser. This lets web pages avoid unsupported features by informing the user their browser is not supported or loading a polyfill. Modernizr aims to provide feature detection in a consistent and easy to use manner that discourages the use of failure-prone browser sniffing.

<span class="mw-page-title-main">Sencha Touch</span> JavaScript framework

Sencha Touch is a user interface (UI) JavaScript library, or web framework, specifically built for the Mobile Web. It can be used by Web developers to develop user interfaces for mobile web applications that look and feel like native applications on supported mobile devices. It is based on web standards such as HTML5, CSS3 and JavaScript. The goal of Sencha Touch is to facilitate quick and easy development of HTML5 based mobile apps which run on Android, iOS, Windows, Tizen and BlackBerry devices, simultaneously allowing a native look and feel to the apps.

Content Security Policy (CSP) is a computer security standard introduced to prevent cross-site scripting (XSS), clickjacking and other code injection attacks resulting from execution of malicious content in the trusted web page context. It is a Candidate Recommendation of the W3C working group on Web Application Security, widely supported by modern web browsers. CSP provides a standard method for website owners to declare approved origins of content that browsers should be allowed to load on that website—covered types are JavaScript, CSS, HTML frames, web workers, fonts, images, embeddable objects such as Java applets, ActiveX, audio and video files, and other HTML5 features.

Leaflet is a JavaScript library used to build web mapping applications. It allows developers without a GIS background to display tiled web maps hosted on a public server, with optional tiled overlays. It can load feature data from GeoJSON files, style it and create interactive layers, such as markers with popups when clicked.

Media Source Extensions (MSE) is a W3C specification that allows JavaScript to send byte streams to media codecs within web browsers that support HTML video and audio. Among other possible uses, this allows the implementation of client-side prefetching and buffering code for streaming media entirely in JavaScript. It is compatible with, but should not be confused with, the Encrypted Media Extensions (EME) specification, and neither requires the use of the other, although many EME implementations are only capable of decrypting media data provided via MSE.

Web Components are a set of features that provide a standard component model for the web allowing for encapsulation and interoperability of individual HTML elements. Web Components are a popular approach when building microfrontends.

<span class="mw-page-title-main">WebAssembly</span> Cross-platform assembly language and bytecode designed for execution in web browsers

WebAssembly (Wasm) defines a portable binary-code format and a corresponding text format for executable programs as well as software interfaces for facilitating communication between such programs and their host environment.

<span class="mw-page-title-main">Babel (transcompiler)</span> Backwards compatible JavaScript compiler

Babel is a free and open-source JavaScript transcompiler that is mainly used to convert ECMAScript 2015+ (ES6+) code into backwards-compatible JavaScript code that can be run by older JavaScript engines. It allows web developers to take advantage of the newest features of the language.

References

  1. Thormeier, Pascal (9 June 2023). Mastering CSS Grid: A comprehensive and practical guide to creating beautiful layouts with CSS Grid. Packt Publishing Ltd. p. 195. ISBN   978-1-80461-616-1.
  2. 1 2 3 Luis Ángel Pérez Castillo (2019). Speaking JavaScript.
  3. "It typically checks if a browser supports an API. If it doesn’t, the polyfill installs its own implementation. That allows you to use the API in either case."
  4. 1 2 3 Bruce Lawson; Remy Sharp. "Introducing Polyfills". Introducing HTML5. pp.  276–277.
  5. 1 2 3 Sharp, Remy (8 October 2010). "What is a polyfill?" . Retrieved 13 January 2012.
  6. Ian Hickson (23 January 2008). "Mistakes, Sadness, Regret". This piece of information makes building an HTML5 compatibility shim for IE7 far easier than had previously been assumed.
  7. "HTML5 Cross browser Polyfills". GitHub . Archived from the original on 28 September 2010.
  8. "What is the difference between a shim and a polyfill?".
  9. Chuck Hudson; Tom Leadbetter (2011). HTML5 Developer's Cookbook. p.  121.
  10. "Core-js". GitHub . 26 October 2021.
  11. "Airbnb-js-shims vs core-js vs core-js-pure vs es5-shim vs es6-shim vs js-polyfills vs polyfill-library vs polyfill-service | NPM trends".
  12. Goodin, Dan (3 July 2024). "384,000 sites pull code from sketchy code library recently bought by Chinese firm". Ars Technica . Retrieved 3 July 2024.
  13. "Polyfill.io Attack Infects Over 110,000 Websites - Spiceworks". Spiceworks Inc. Retrieved 1 July 2024.
  14. "navigator.id". Mozilla Developer Network. 30 June 2012. Archived from the original on 3 August 2012. Retrieved 9 July 2012.
  15. "Hyphenopoly.js". GitHub . 25 September 2022.