Native HTML5 Component Development using Web Components & Polymer – Whitepaper

A white paper on W3C standards Web Components and Polymer Framework. Learn about Custom Elements, Shadow DOM, Templates and HTML Imports.

Introduction

Our expectation from technologies is never-ending; we keep on revolutionizing the way we do our web development and enrich users’ experiences. Browsers have come a long way and they have implemented the ever-changing standards.

In the above “web development evolution infographics”, we can see a repeating pattern of induction of external libraries and their refinement, followed by its support in the native web technologies.

When AJAX evolution took place 10 years back, we started with a basic JavaScript program to leverage the power of AJAX and we ultimately ended up with very high-level libraries like Mootools and JQuery. And not that far in the future, we have better standards to do that natively.

Similarly, when the evolution of the Rich Internet Application (RIA) started, we required several ready-to-use UI components. JQuery UI and several other libraries had supported the need efficiently. In the time frame of a few years, the web standard committee has introduced several ready-to-use components as native elements in the browser with the help of web standards (HTML5). For e.g. date and time picker is a very common UI component included in our web page using libraries like JQuery UI and others. But now we have a date picker inbuilt into the browser as a native HTML element and we don’t need any external library anymore for this purpose.

In 2015, web applications are not only complex but they should have qualities like good performance and user experience on mobile devices. Interoperability is one attribute but we also wanted to distribute our components efficiently to other applications. Iframe or other hacks are impacting the easiness of developing web applications.

In this white paper we will try to answer the following questions:

  1. What are some major problems which Web Components standards are trying to solve?
  2. What is Polymer & Why we should use it?
  3. Polymer: When to use & When not to use?
  4. Is it the right time to use these technologies in our next project?

Problems & Solutions

In this section we will be talking about a few fundamental problems which we face while developing web applications and how they have been solved through four specifications of Web Components:

  1. Custom Elements
  2. Shadow DOM
  3. Templates
  4. HTML Imports

The problem of syntax & reusability

How do we use reusable components like Model, Window, Slider, Label, Progress Bar, and others in web pages?

We use some third-party plugins or libraries for it. A few very famous third-party libraries are Twitter Bootstrap, Facebook React, Adobe Topcoat, Zerb Foundations, and many others.

All of these frameworks have their own semantics to create components on web pages. All of them need the support of CSS and JS. We add CSS and JS of these libraries on web pages where we intended to use their UI or non UI components.

When we wanted to use these components we just copy and paste the code snippets. Usually, these are some DOM elements, style Classes, and JavaScript codes.

A few problems in the way to use components are:

  1. A lot of repetitive codes required
  2. A lot of repetitive codes make changing complex and error-prone

Web Components standards have introduced the concept of a full-fledge custom element. Before the Web Component standard, we may create custom elements, but the technique was not straightforward. According to W3C Custom Element Specification (Ref):

Though it was long possible to create DOM elements with any tag names in HTML, these elements weren’t very functional. By giving Web developers the means to both inform the parser on how to properly construct an element and to react to life cycle changes of an element, the specification eliminates the need for DOM-as-a-render-view scaffolding that has to exist today in most web frameworks or libraries.

We still have to define these custom elements and import that into our web pages, but for doing so we don’t need any external library or inclusion of JS and CSS individually.

These custom elements can also extend existing elements and give them some new behavior also.

An example of a custom element that makes text italic and bold using a custom element bold-italic has been given:

( JSFiddle URL For This Example: https://goo.gl/02OJlm )

This is a very basic example of Web Components Custom Element, but powerful enough to convey the following messages:

  1. Easy Native methods to define new reusable HTML tag
  2. Use like first-class HTML tag

It’s noteworthy that we can do a lot of things with Custom Element, for that we need to look into its specifications.

Problem of encapsulation

When we use external library components in our web pages, we may have to resolve the conflict of JavaScript and CSS between the parent web pages and components. We had seen people spending hours resolving these conflicting situations.

Not being able to encapsulate components from the rest of the page style and javascript behavior is a very big problem. They don’t possess their own identity, once they are bought on a web page they are just another element.

The iframe is a hack that people use to resolve these conflicts if components become too big to handle.

Web Components standards had introduced a way to put an end to these issues, known as Shadow DOM.

In our earlier example if you inspect the bold-italic element in Google Chrome Developer Tools, you can see something like it:

We can see components now treated as just another DOM element of the document. Its style can easily be controlled by the parent documents. If this component is written with hundreds of lines of JavaScript and CSS, there is a chance it can easily get conflicted with the parent web page’s JavaScript and CSS.

Now we will use shadow DOM in our bold-italic custom element to encapsulate them from the parent web page.

With Shadow DOM, elements can get a new kind of node associated with them. This new kind of node is known as Shadow Root. An element that has a Shadow Root associated with it is called Shadow Host. Content of a Shadow Host isn’t rendered; Content of Shadow Root is rendered instead.

Shadow DOM provides us a new pattern to develop components with true encapsulation. This example is a small demonstration of Shadow DOM capabilities. Shadow DOM has several features for different use cases.

Few important benefits Shadow DOM provides to the custom elements or any widget:

  1. No Style Sheets conflict with parent web page
  2. No JavaScript conflict with the parent web page
  3. We can choose to use the parent web page style sheet and JavaScript at our discretion

The problem with dynamic HTML templates

The template is a basic feature provided by several languages and web client frameworks to define a format for some output which is used again and again. It is created only once but used several times in the life cycle of an application. There are several web client template libraries like mustache, handlebar, and others available.

This need/problem is so common, that Web Components Standards had introduced HTML Templates standard. According to WhatWG HTML Templates specification:

A new element which describes a standard DOM-based approach for client-side templating. Templates allow you to declare fragments of markup which are parsed as HTML, go unused at page load, but can be instantiated later on at runtime.

A few salient features provided by Templates are (Ref):

  1. Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render.
  2. Any content within a template won’t have side effects. The script doesn’t run, images don’t load, and audio doesn’t play,…until the template is used.
  3. Content is considered not to be in the document. Using document.getElementById() or querySelector() in the main page won’t return child nodes of a template.
  4. Templates can be placed anywhere inside of <head>, <body>, or <frameset> and can contain any type of content which is allowed in those elements. Note that “anywhere” means that <template> can safely be used in places that HTML parser disallows…all but content model children. It can also be placed as a child of <table> or <select>.

An example demonstrating the use <template> and Shadow DOM in custom element <my-name> :

We have defined one template and used it with a custom element <my-name> three times. This custom element does some font color and size customization.

JavaScript code for the custom element:

( Full example: https://goo.gl/0Br8rV )

The problem of importing HTML resources

We can import resources on a web page depending on the type

  1. For  JS <script src>
  2. For CSS <link rel="stylesheet">
  3. For images <img src>
  4. For Videos <video>
  5. For Audio <audio>

For importing HTML to a web page we have:

  1. IFrame – Used broadly but it’s heavyweight and it lives in a different context than the current web page. Customization of content according to the outer parent documents is always challenging.
  2. AJAX – We can load HTML using XMLHTTPRequest but it is overkill to use JavaScript to load HTML.
  3. and all sorts of other hacks

For solving the problem of HTML, import Web Components have been introduced Import standards.

As per HTMLRocks Web Components article (Ref)

HTML Imports, part of the Web Components cast, is a way to include HTML documents in other HTML documents. You’re not limited to markup either. An import can also include CSS, JavaScript, or anything else an .html file can contain. In other words, this makes imports a fantastic tool for loading related HTML/CSS/JS.

This is a very effective way of including HTML inside an HTML. Let’s have a look at a small example of how we can use import.

Import used with existing <link rel=””> element.

Web Component’s four standards complement each other and give us the flexibility in building, encapsulating, and distributing reusable web components in a way we never did before.

What is Polymer & why we should use it?

As a web app developer, we should not use Web Components standards directly in our application. As you had noticed, objects and methods exposed by the Web Components Standards are very bare. Hence we should leverage these standards through some high-level frameworks like Polymer, x-tags, and others. It helps us in filling the gap which these standards have.

According to our analysis, It is a very non trivial task for developing a full-fledged application using Web Components standard libraries, hence most of the Web Component adaptors have used frameworks like Polymer to develop applications.

Polymer is a full-fledged web client framework created on top of W3C Web Components standards. They came with polyfills hence they are compatible in all browsers despite they don’t support Web Components standards.

For projects where we develop custom Web Components elements for third parties’ consumptions, they may use Web Components without using any high-level framework.

It’s also prevalent that, in the coming days we will be seeing several high-level frameworks like Polymer getting developed. As well as existing libraries like Bootstrap, JQuery or others will have the option to use in applications as Web Component elements through import standards.

As of now, Polymer is the only framework based on the Web Components standard which is available to a scale.

Polymer is the best way to use Web Components because it gives Polyfills for Browser interoperability. It is also good for quick development, because, they give several ready-to-use elements required to build apps of any type.

Skate and Bosnic are also two web component frameworks through evolving.

Polymer: When to use & When not to use?

Polymer library provides us following benefits on the top of Web Components:

  1. Providing a high-level framework based on Web Component standards for rapid development of web clients.
  2. They provide several ready-to-use elements for UI themes, UI widgets, other UI components, accessibility, third-party API integration, animation, or other elements. There is a huge library of elements, with several elements added daily.
  3. They provide interoperability in all browsers with native support for Web Components or not, using Polyfills libraries.
  4. Better performance in Browsers like Safari, and Internet Explorer, which don’t support Web Components natively. With release 1.0, the size of polymer libraries and Polyfills libraries reduced drastically. The performance of the application is very high with a brand new, lightweight shadow DOM shim called shady DOM, which let you avoid the complexity, size, performance penalty, and invasiveness of the shadow DOM polyfill.
  5. Several high-level functions are available to build Custom Elements.
  6. Last but not least, Polymer comes with Polymer Starter Kit, a downloadable zip. This starter kit provides boilerplate code to start developing applications on Polymer quickly. It consists of general-purpose app elements, builds chain, testing tools, app theming, the choice to be framework-free or compatible, responsive layout, live browser reloading, and Material design readiness. This starter kit helps developers in getting productive very quickly, reducing further development time.

Let’s talk about a few reasons why we will not use Polymer.

  1. It’s very cutting edge and it will keep on evolving for a couple of more years. In case we don’t want to build an app on a framework that is evolving very rapidly.
  2. Limited availability for skilled developers.
  3. Multiple requests were made to the server due to internal imports of the components (HTML files)
  4. Web Components standards are not supported by all the browsers.
  5. If Polyfills file size is a concern, which is in the range of 40 to 60 KB when Gzipped
  6. Performance issues due to Polyfills

Is it the right time to start leveraging these standards?

Promoters of Web Component standards are Google and Mozilla, they are working with W3C to standardize it, so browsers can support it widely. It makes sense because if the browser will natively support these standards then the performance of custom element creation or inclusion of external HTML will increase much.

Browser support to Web Components Standards Matrix is given below:

As of now, Chrome and Opera (Using Chromium rendering engine) browsers support all standards while other browsers had started showing their interest.

According to Web Components’ official website, we can use Web Component Polyfills known as webcomponents.js , and start using these standards without worrying about their implementation in the browser or not. This JS file has a size of 117KB as minified and 34KB when gzipped.

Even if all browsers don’t support these standards, they solve a few very important problems and we should start using these standards to build an application where their inclusion makes a lot of sense.

According to our analysis game, education, media, advertisement, and technology startup markets had started adopting it in their web client development. There are few known technology products whose web user interface was developed using Polymer.

We feel the web development team had started opening up to use Polymer and Web Components for their upcoming projects.

There are several internal and external projects of Google that adopted Polymer as their core web framework. This also shows the confidence of google in this web framework.

For e.g. Google Translate Community and Google Music and others.

The polymer released its first major version at May 2015 Google IO event, which they called production-ready. It is very early to say which specific industry will take lead in its adoption.

As per our analysis, a Web Component-based framework like Polymer had introduced a browser native web client development framework, which will change the way we were developing in past as well as how it was performing. These changes are for good as they will enable pure component-based UI development, which results in a good product in less time.

We can use Polymer very efficiently for the following use case:

  1. Sophisticated games with WebGL (E.g. Google Santatracker app 2014)
  2. Interactive Components
  3. Single Page Application (Without using any Specialised SPA framework like AngularJS and others)
  4. Components for third parties
  5. Admin Interfaces
  6. Enterprise Web Portals
  7. and Other

Conclusion

Web Components standards are useful and they will adopt widely in the future, once all browsers will have these standards implemented. Even with polyfills, it provides a few very useful concepts for easing out web developments.

It will definitely replace iframe-based component development. It will be a huge relief for third-party applications that always struggle in integrating their web components.

In my point of view, we should start leveraging the development of the reusable components using Web Component-based frameworks like Polymer or others. Several web product companies like Github, Google, and others have started using these in their projects.

References

  1. HTML5Rocks Custom Elements Article
  2. HTML5Rocks Shadow DOM Article
  3. HTML5Rocks Template Article
  4. HTML5Rocks Import Article
  5. Web Components official website
  6. Polymer project website
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top