Native HTML5 Component Development using Web Components & Polymer: White Paper

Lego Color BricksIntroduction

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

Native-HTML5-Component-Development-using-Web-Components-Polymer-2.jpg

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 basic JavaScript program to leverage 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 evolution of 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 few years web standard committee have introduced several ready-to-use components as native elements in the browser with the help of web standard (HTML5). For e.g. date and time picker is a very common UI component which included in our web page using libraries like JQuery UI and others. But now we have date picker inbuilt in browser as a native HTML element and we don’t need any external library any more 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 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 few fundamental problems which we face while developing web applications and how they have solved through four specifications of Web Components:

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

Problem of syntax & reusability

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

We use some third-party plugins or library for it. 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 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.

Few problems in the way to use components are:

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

Web Components standard have introduced the concept of full fledge custom element. Before Web Component standard we may can create custom element, 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 behaviour also.

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

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

Native-HTML5-Component-Development-using-Web-Components-Polymer-3.jpg

This is a very basic example of Web Components Custom Element, but powerful enough to convey 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 it’s 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 parent web page and components. We had seen people spending hours resolving these conflicting situations.

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

Iframe is a hack which 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 bold-italic element in Google Chrome Developer Tools, you can see something like it:

Native-HTML5-Component-Development-using-Web-Components-Polymer-4.jpg

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

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

Native-HTML5-Component-Development-using-Web-Components-Polymer-5.jpg

Native-HTML5-Component-Development-using-Web-Components-Polymer-6.jpg

With Shadow DOM, elements can get a new kind of node associated with them. This new kind of node known as Shadow Root. An element that has a Shadow Root associated with it called Shadow Host. Content of a Shadow Host isn’t rendered; Content of Shadow Root 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 have several features for different use cases.

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

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

Problem of dynamic HTML templates

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

This need/problem is so common, 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.

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. Script doesn’t run, images don’t load, 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 use <template> and Shadow DOM in custom element <my-name> :

Native-HTML5-Component-Development-using-Web-Components-Polymer-7.jpg

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

JavaScript code for the custom element:

Native-HTML5-Component-Development-using-Web-Components-Polymer-8.jpg

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

Problem of importing HTML resources

We can import resources in web page depending on 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 in a web page we have:

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

For solving problem of HTML import Web Components have 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 very effective way of including HTML inside an HTML. Let have a look into small example of how we can use import.

web-components-import-code

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

Web Components four standards compliments each other and gives us flexibility of building, encapsulating and distributing reusable web components in the 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 framework like Polymer, x-tags and others. It helps us in filling the gap which these standards have.

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

Polymer is a full-fledged web client framework created on the 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 can use Web Components without using any high level framework.

It’s also prevalent that, in 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 option to use in application as Web Component element through import standard.

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

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

Skate and Bosnic are also two web component frameworks though 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 standard for rapid development of web client.
  2. They provides 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 browser with native support for Web Components or not, using Polyfills libraries.
  4. Better performance in Browser like Safari, Internet Explorer, those doesn’t support Web Components natively. With release 1.0, size of polymer library and Polyfills libraries reduced drastically. Performance of the application is very high with brand new, lightweight shadow DOM shim called shady DOM, that let you avoid the complexity, size, performance penalty, and invasiveness of the shadow DOM polyfill.
  5. Several high level functions 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 application on Polymer quickly. It consists of general purpose app elements, build chain, testing tools, app theming, choice to be framework free or compatible, responsive layout, live browser reloading and Material design readiness. This starter kit helps developer in getting productive very quickly, reducing further development time.

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

  1. It’s very cutting edge and it will keep on evolving for couple of more years. In case we don’t wanted to build app on the framework which is evolving very rapidly.
  2. Limited availability for skilled developers.
  3. Multiple requests made to 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 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 browser can support it widely. It make sense because if browser will natively support these standards than performance of custom element creation or inclusion of external HTMLs will increase much.

Browser support to Web Components Standards Matrix given below:

Web Components Browser Compatibility Matrix

As of now Chrome and Opera (Using Chromium rendering engine) browser supports all standards while other browser 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 its implementation in browser or not. This JS file has a size of 117KB as minified and 34KB when gzipped.

Even all browsers doesn’t support these standards, they solve few very important problems and we should start using these standards to build application where their inclusion make 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 developed using Polymer.

We feel 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 adopted Polymer as their core web frameworks. This also shows confidence of google in this web framework.

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

Polymer had released its first major version in 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, 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 it will enable pure component based UI development, which result in good product in less time.

We can use Polymer very efficiently for 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 it will adopted widely in the future, once all browsers will have these standards implemented. Even with polyfills it provides 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 who always struggle in integrating their web components.

In my point of view, we should start leveraging the reusable components development using Web Components based framework 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

Leave a Comment

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