Polyfill
Polyfills are code components that make newer web features usable in browsers that do not natively support such features. This article explains what these practical code components are and how you can use them.
What are polyfills and which languages can they be written in?
A polyfill, sometimes referred to as a Polyfiller, is a code block of varying complexity that makes modern HTML, CSS or JavaScript functions available in older browsers that are unable to support them natively. Most polyfills are written in JavaScript, however, other web programming languages can also serve as the basis for filler scripts. Some of the most important features that polyfills make available across different web browsers are HTML5 components like the bitmap-based canvas elements for graphics, charts and animations.
The term “polyfill” is derived from the popular British brand Polyfilla, which is a filling compound for renovation and restoration work. Web developer Remy Sharp saw a fitting comparison between the filler and these useful workaround codes, since the purpose of both is to fill in gaps. With the latter, the gaps to be filled are gaps in browser functionality. The concept was coined in Sharp’s 2009 book “Introducing HTML5”, which he co-authored with Bruce Lawson. Polyfill subsequently established itself as the official designation for such code components.
What types of polyfills are there?
The fact that the term polyfill is closely associated with HTML5 is no coincidence. With its advanced features that have rendered, among other things, the necessity of flash videos passé, the fifth version of the hypertext markup language has become a permanent feature of the web. However, the support for HTML5 in browsers has developed rather slowly. In addition to the polyfills created for HTML5 elements, polyfill code blocks are also used to integrate the following web elements:
- SVG graphics: The SVG format SVG (Scalable Vector Graphics), which the W3C consortium began recommending as the standard format for vector graphics in 2001, first gained traction with HTML5. But because many browsers have yet to provide support for this format, there are SVG polyfills such as svgweb.
- ECMAScript: ECMAScript is the standardized core of JavaScript and is regularly updated to expand the language’s functionality. Features like Promise objects or Symbol functions are made available in older browsers through polyfills like the JavaScript standard library core-js.
- Web storage: Cookie alternatives like local storage (long-term storage on client-side) and session storage (storage limited to the current session), collectively known as web storage or DOM Storage, are not supported by all browser versions. The MIT-licensed webstorage-polyfill is a well-known solution for this issue.
- Cross-Origin Resource Sharing (CORS): CORS allows web applications to access web resources located outside of one’s own server. Many older browsers do not support this data exchange. The JavaScript package XDomain and the CORS polyfill XHook can help address this.
- CSS (Cascading Style Sheets): For years, CSS has been one of the most important tools for designing the visual layout of websites. Over time, stylesheets have become more versatile, making polyfills popular for interfacing with older browsers. One of the best-known tools is css-polyfills.js.
- Geolocation: For a long time, the Geolocation API (used to transmit a user’s location) was not supported by browsers and could only be used with the help of an additional browser plugin. With a polyfill, you can provide this functionality to users with older browser versions that do not natively support the API.
To simplify and optimize the use of polyfills, services like the Polyfill.io project use content delivery networks (CDNs) to deliver the scripts. However, as of early 2024, there have been significant issues with malware being distributed through the CDNs used by Polyfill.io. If you are using this service, you should remove any code you have from the Polyfill.io project from your website.
How are polyfills used? (Code examples included)
You can directly embed polyfill JavaScript code or polyfill scripts into the HTML document of a website. These integrate seamlessly into the existing source code and are only executed if the browser does not support the particular web feature. This is typically done using JavaScript’s if
-statement to check for missing support. The lack of support can then be turned into a condition for activating the script. In the following two examples, we’ll illustrate how to implement this and show you what the general structure of a polyfill looks like.
Example 1: Polyfill for the JavaScript method startsWith()
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
javascriptThis small JavaScript snippet allows the calling browser to use the startsWith()
method, even if it doesn’t support it natively. This method, part of the ECMAScript 6 specification, checks whether a string begins with the character or character series of another string. If it does, it will return “true”, otherwise it will return “false”.
You can find a more complex, optimized version for integrating startsWith()
on the GitHub page of developer Mathias Bynens.
The code presented here will not work if the web client blocks JavaScript or has the scripting language disabled in its settings.
Example 2: Web storage polyfill
This JavaScript polyfill is a simple coding solution that makes local and session storage available in older browser models.
if (typeof window.localStorage === 'undefined' || typeof window.sessionStorage === 'undefined') {
(function () {
var data = {};
var Storage = function (type) {
function setData() {
// Implement the logic to set data into storage
var storageData = JSON.stringify(data);
document.cookie = type + '=' + storageData + ';path=/';
}
function clearData() {
data = {};
setData();
}
return {
length: 0,
clear: function () {
clearData();
this.length = 0;
},
getItem: function (key) {
return data[key] === undefined ? null : data[key];
},
key: function (i) {
var ctr = 0;
for (var k in data) {
if (ctr == i) return k;
ctr++;
}
return null;
},
removeItem: function (key) {
delete data[key];
this.length--;
setData();
},
setItem: function (key, value) {
data[key] = value + '';
this.length++;
setData();
}
};
};
// Set the local and session storage properties inside the window object
if (typeof window.localStorage === 'undefined') window.localStorage = new Storage('local');
if (typeof window.sessionStorage === 'undefined') window.sessionStorage = new Storage('session');
})();
}
javascriptThe code provided above is an Immediately Invoked Function Expression (IIFE). Before the browser loads it, however, an if
command in the first line of code checks whether the client natively supports the web storage technologies. If it does, the if
statement will return a false value, because the types for local and session storage are already defined. This results in the polyfill being discarded.
- Simple registration
- Premium TLDs at great prices
- 24/7 personal consultant included
- Free privacy protection for eligible domains