Polyfill - Code That Makes Everything Work

There is something magical about programming. It is a pity that new applications will not work in old browsers. Wait a moment... what about polyfills?

Peanuts

From this article you will learn:

  • What is a Polyfill?
  • What do polyfills and shim.gif have in common?
  • How is a Polyfill built?

Our world is quite old. The age of Earth is estimated at around 4.5 billion years. Even so, the events that followed one another overlap quite strongly, creating a beautiful and long, and above all coherent, story. It is very likely that not all modern organisms would manage in Earth's atmosphere from billions of years ago. You may think that I pulled this reference out of a hat - what does it have to do with today's topic?

Just as a human would not be able to live on Earth 3.5 billion years ago, a program written today would not run in a browser from the 90s. Supposedly the same environment, and yet some of its aspects have changed completely. Where does this come from? Above all, from development. The ecosystem and atmosphere of our planet change. Programming languages and their specific implementations in browsers change in the same way. Even browsers from the same period could have different approaches to the same topics.

What Is a Polyfill?

Let us go deeper into this topic. Browsers released over the years based their implemented language standards on the latest guidelines rather loosely. The problem did not concern only JavaScript - although it concerned JavaScript most often. For example, IE7 did not support the CSS text-shadow property. A similar effect could still be achieved by using the appropriate filters available in IE.

css
.text {
  text-shadow: 1px 1px 0 #000; /* does not work in IE7 */
	filter: DropShadow(Color=#000000, OffX=1, OffY=1); /* works in IE7 */
}

The technique used here is so-called polyfilling, meaning the use of code that allows us to use a given feature even when it has not been implemented.

We can encounter such a situation in two cases: in old browsers that are no longer developed, and also in new ones, when vendors are not able to keep up with adding new features from language standards, or consciously choose not to. While the first case is important from a business perspective, the second improves the so-called developer experience - giving us more opportunities to write in a newer way and with new technical capabilities.

A polyfill (in Polish literature you may encounter the word "uzupełniacz") is code whose task is to implement a new function that does not exist or is not supported. Such code should provide backward compatibility for old browsers. Interestingly, this word does not exist in English as an ordinary word - it is a neologism that was used for the first time in 2009 in Remy Sharp's book Introducing HTML5.

Shim and Shiv

It is worth mentioning that in 2009 the term shim already existed and could successfully have replaced the new term coined by Sharp. Sharp stated, however, that he needed a tool that would work more automatically. A shim is a piece of code whose task is to fix a non-working feature - in a way, it achieves that, but it requires a certain amount of work. The result is not automatic, and that is what Sharp expected.

To understand what a shim is, we need to move back a little in time to the moment when we were creating layouts based on tables. To preserve an empty cell that represented the right amount of spacing, it had to be filled with something - whitespace was not an option, so transparent GIFs with dimensions of 1 pixel by 1 pixel were added. Such files were often called shim.gif. This of course provided backward support, but it did not happen automatically - it required manually adding such a file. By the way, a tool for collecting data is based on a similar mechanism: Facebook Pixel.

Shiv works on similar assumptions, but it is most often a JavaScript file whose task is to overwrite an existing interface. The best-known Shiv code is HTML5shiv, which at one time overwrote the HTML interface in Internet Explorer browsers so that new syntax could be used in older browsers.

How Is a Polyfill Built?

A good polyfill should work only when a given feature does not exist in the browser. It definitely should not be loaded when the browser supports what the polyfill adds. So the first thing it should do is start with a condition. Checking directly whether a given feature, especially one existing in the global scope, exists is quite risky because it may return an error if the feature is missing. Let us try to create a polyfill for the confirm function.

js
if (confirm) { // ReferenceError

}

A condition written this way will return an error in older browsers. The typeof operator is useful for handling this problem.

js
if (typeof confirm === 'undefined') {
	confirm = function () { /* ... */ }
}

We can achieve the same thing by referring to the object through the global object. For example:

js
if (!window.confirm) {
	confirm = function () { /* ... */ }
}

It is worth noting that the window object will not always be available, for example in environments other than browsers. For this reason, it is recommended to avoid such a direct reference.

The situation is different with functions assigned to a specific prototype. Let us look at the most popular function in the array prototype: map.

js
if (!('map' in Array.prototype)) {
	Array.prototype.map = function () { /* ... */ }
}

The code placed inside such a polyfill should not create any side effects, because adding such code to an application carries serious and unpleasant consequences. What is more, the function being filled in should precisely reflect the behavior of the original and accept exactly the same arguments. Otherwise, this may lead to many unpleasant and difficult-to-catch bugs.

URLs?

Since 2009, polyfills have settled into our environment for good. We do not have to create them from scratch every time. There are many libraries that have been creating polyfills for everything for years. The first example collection of polyfills was jQuery, which indirectly added support for many features so that pages could work the same way everywhere.

Today we can find sets of polyfills, for example, in Babel. An interesting project is polyfill.io, which lets us create a file containing only the polyfills we need in our project.

Updated on 01 July 2024

I mentioned above that one of the interesting solutions related to using polyfills is the polyfill.io library. That project was an open-source project that was sold some time ago to a Chinese company. Right after taking over the domain, this entity modified the polyfill.js file within the acquired library in such a way that both the code and the domain redirected users to malicious websites.

What lesson does this give us? Above all, we should not blindly trust external providers, especially those we do not pay for the quality they deliver.

I would also add from myself that it is worth distinguishing the library itself, around which the current controversy is developing, from the technique of writing code that a polyfill itself is.

Summary

Earth changes much more slowly than the world of programming. The time required for life to adapt is extended compared with the fairly dynamically changing world of programming. The concepts of polyfills, just like the earlier shim and shiv, are meant to provide backward compatibility so that even old environments can provide a substitute for modernity and allow us to open what without them would throw a white screen and a red note in developer tools.

Sources

Share this article:

Comments (2)

  • Mateusz Jabłoński

    29 czerwca 2024 o 07:45

    Nie poleciłem polyfill.io ;) Napisałem, że jest ciekawym projektem (w zasadzie był jak dotąd) - cały artykuł mówi o koncepcji polyfill'i jako fragmentów kodu. To co się wydarzyło w temacie tej biblioteki to cenna lekcja dla wszystkich. Również dla mnie - powinniśmy być bardziej świadomi tego, co wkładamy do swoich projektów i lepiej szacować ryzyko.

  • hehe

    29 czerwca 2024 o 07:42

    No i masz - już wiesz czemu nie poleca się głupich rzeczy? ;)

You may be interested in

If this article interested you, check out other materials related to it thematically. Below you will find articles and podcast episodes authored by me, as well as books I recommend that expand on this topic.

Magia Pixel Perfect by kudou
Article
2022-08-11

The Magic of Pixel Perfect

In the days when we dialed into the Internet, an approach was born that defined web development for many years. Today it is not quite as popular, but in my opinion it is still worth knowing and understanding. Let's talk about the magic of pixels.

Read more
Matryoshka Dolls by Frankenvrij
Article
2021-08-13

Currying

Functional programming is almost as popular as object-oriented programming. Many concepts from object-oriented programming have entered programming in general so deeply that sometimes we no longer even notice where a given approach comes from. Functional programming also has its interesting concepts, and currying is one of them. In this article I use examples to show how currying works and what problems it can help us solve.

Read more
Editor by Maica
Article
2020-07-09

How to Build Your Own Text Editor in the Browser?

A programmer's work is about solving problems. Programming languages are our tools. By using them we can create new solutions, but also new tools. Text editors are definitely such tools. Today we will try to write our own.

Read more

Zapisz się do newslettera

Bądź na bieżąco z nowymi materiałami, ćwiczeniami i ciekawostkami ze świata IT. Dołącz do mnie.