Polyfills are code com­po­nents that make newer web features usable in browsers that do not natively support such features. This article explains what these practical code com­po­nents 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 Poly­filler, is a code block of varying com­plex­i­ty 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 pro­gram­ming 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 com­po­nents like the bitmap-based canvas elements for graphics, charts and an­i­ma­tions.

Note

The term “polyfill” is derived from the popular British brand Polyfilla, which is a filling compound for ren­o­va­tion and restora­tion work. Web developer Remy Sharp saw a fitting com­par­i­son 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 func­tion­al­i­ty. The concept was coined in Sharp’s 2009 book “In­tro­duc­ing HTML5”, which he co-authored with Bruce Lawson. Polyfill sub­se­quent­ly es­tab­lished itself as the official des­ig­na­tion for such code com­po­nents.

What types of polyfills are there?

The fact that the term polyfill is closely as­so­ci­at­ed with HTML5 is no co­in­ci­dence. 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 con­sor­tium began rec­om­mend­ing 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.
  • EC­MAScript: EC­MAScript is the stan­dard­ized core of JavaScript and is regularly updated to expand the language’s func­tion­al­i­ty. 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 al­ter­na­tives like local storage (long-term storage on client-side) and session storage (storage limited to the current session), col­lec­tive­ly known as web storage or DOM Storage, are not supported by all browser versions. The MIT-licensed web­stor­age-polyfill is a well-known solution for this issue.
  • Cross-Origin Resource Sharing (CORS): CORS allows web ap­pli­ca­tions 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 in­ter­fac­ing with older browsers. One of the best-known tools is css-polyfills.js.
  • Ge­olo­ca­tion: For a long time, the Ge­olo­ca­tion API (used to transmit a user’s location) was not supported by browsers and could only be used with the help of an ad­di­tion­al browser plugin. With a polyfill, you can provide this func­tion­al­i­ty to users with older browser versions that do not natively support the API.
Note

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 sig­nif­i­cant issues with malware being dis­trib­uted 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 seam­less­ly into the existing source code and are only executed if the browser does not support the par­tic­u­lar 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 ac­ti­vat­ing the script. In the following two examples, we’ll il­lus­trate 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;
    };
}
javascript

This 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 EC­MAScript 6 spec­i­fi­ca­tion, 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 in­te­grat­ing startsWith() on the GitHub page of developer Mathias Bynens.

Note

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');
    })();
}
javascript

The code provided above is an Imme­di­ate­ly 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 tech­nolo­gies. 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.

$1 Domain Names – Register yours today!
  • Simple reg­is­tra­tion
  • Premium TLDs at great prices
  • 24/7 personal con­sul­tant included
  • Free privacy pro­tec­tion for eligible domains
Go to Main Menu