Polymer / Web Components: using together

Web components

Exploring new methods to improve my code in JS and increase performance I started to look through some new libraries. Our CTO told me that Polymer has some awesome and interesting solutions for speeding up apps and using the latest browser ‘Web Components’ (Custom elements, Shadow DOM, HTML templates and HTML import): so now you can create you own elements or extend old elements. Also they will be very fast and reusable (you can use it in different ways). So, that is what the future will look like, in my opinion. You can learn more about Web Components here. Polymer is a great example of Web Component implementation in the real world.

What is Polymer?

So, what is Polymer and where do we start with it? Polymer is a library (its developers call it a set of polyfills and ‘syntax sugar’) for creating and using Web Components. Check out this big catalog with great documentation of Polymer’s components. It looks fantastic doesn’t it, but how can it help us? Let me show you.

A quick example

Firstly though, take a look at this small example of a Polymer app. Of course, all the components can easily be made in accordance with Google’s material design style and Polymer helps with this by giving us templates, default styles etc. What about compatibility? Polyfills provide support on evergreen browsers for APIs that aren’t universal yet. From the official site we can see that Polymer makes it simple to create web components declaratively. Custom elements can leverage Polymer’s special features to reduce boilerplate and make it even easier to build complex, interactive elements, for example:
– Registering elements
– Lifecycle callbacks
– Property observation
– Local DOM template
– Data binding

Code time

Okay, let’s write some code.

Here you can see that we’ve imported 3 html-templates. Before we see them let me tell you that Polymer uses an unusual way to write code, so for some developers it can look rather maze like. In the official docs you’ll find that the basic Polymer element definition looks like this:

But it’s not the end. Let’s use some components with ready style-templates in material design and we will get my-el-0.html:

Embarrassed? I want to say that we include my-el-3.html in the my-el-0.html. Here is my-el-3.html:

You can take a look the my-el-1.html here:

And I want to finish with my-el-2.html that includes 2-way data binding variable ‘owner’.