Get Ready for Web Components!

The world of web development moves at a blistering pace. New technologies emerge thick and fast. Often we developers find ourselves desperately wishing there was a “pause life” button to momentarily halt the deluge of new tools long enough to absorb the latest in-vogue feature / framework / API before the next arrives. It’s enough to drive anyone a little crazy.

developer-challenges

 

The next big thing appearing on the developer radar is Web Components. These are a little different to the other recent tools and goodies to hit the development landscape in that they’re widely regarded as something that ALL front-end web developers should hit the pause button for and take notice of. When you hear things like “the biggest change to web development in ten years” and “bigger than HTML5” being said, you know that this isn’t your average, everyday toolset. We’ll come back to Web Components shortly, first let’s spell out the issues they are here to address.

The Problem

New tools are great but for developers they also mean there’s new code to learn, increasingly bloated webpages (each additional library / framework used increases page load times) to deal with, excessive (and often hard to maintain) code, compatibility problems between libraries… and the list goes on.

For many years everything on a web page was encapsulated in <div> (divider) or <span> tags (or worse – tables, *shudders), which made code a bit of a nightmare to read and maintain (see the markup soup below).

div-soup

 

Then HTML5 came along and things looked brighter with the introduction of semantic tags. Content could now be framed within much more appropriately named tags such as <article>, <section>, <video>, <footer>. To quickly show why it’s far from ideal, take a look at the below code from Twitter’s popular Bootstrap development framework. This HTML is pretty much the minimum required to setup Bootstrap’s carousel / rotating image feature (taken from the Bootstrap website):

bootstrap-carousel-markup-soup

Not particularly friendly to the eyes, is it? AND this has been abbreviated for brevity. Then there’s the accompanying CSS and JavaScript which needs to be placed around the web page in order to make the thing work. Despite the great functionality, it’s messy.

A Solution

What if, instead, we could just define the carousel like so:

carousel-html-tag

That’s so much neater, more readable and easier to maintain. Now it has to be said that HTML5 has already begun down the path of creating elements like this. The audio tag, for instance, looks remarkably similar:

audio-tag

 

 

This simple snippet of HTML results in these audio players being displayed in the browser:

html5-audio-ui

 

 

 

 

 

 

 

So where is the code for the play button, time display, progress bar, and so on, hidden? We’ll come back to that in a second. There are a few other elements which follow this pattern – the date and time inputs, for example. Code goes in:

html-date-time-tag

 

 

And these pop out:

html-date-time-ui

 

What type of sorcery is this?!

sorcery

 

The Shadow DOM

These elements all share one thing in common. The bulk of the code behind them is hidden from view – it’s in the shadows, more specifically hidden in what is known as the Shadow DOM (if you’re not sure what the DOM is, take a look here). The shadow DOM is a new addition to the HTML spec in which HTML markup, CSS and JavaScript is encapsulated and therefore kept separate from the regular DOM. The Shadow DOM is just one piece of the Web Components pie.

shadow-dom

 

HTML Templates

The next piece are template tags. Code which is housed in between template tags (including CSS and JavaScript) is completely inert, so the browser doesn’t render it in the page. This is where you’ll find the inner workings of elements that utilise the Shadow DOM.

html-template

 

 

 

 

 

However, with a bit of JavaScript, we can clone the content of the template tag and inject it into the page whenever we need. Think of them as a blueprint.

HTML Custom Elements

The next piece of the puzzle is Custom Elements, which is what we looked at earlier, specifically the carousel tags we hypothesised could / should house a carousel gallery. One thing to note is these elements follow a naming convention and MUST (to avoid any possible conflicts with other elements) contain a hyphen “-“ so the carousel tag shown earlier would have to become “carousel-gallery” or something similar to be accepted.

Custom Elements allow us to write markup that makes sense. Their functionality and presentation can be declared in the Shadow DOM, allowing us to create unique APIs for each element. But not only that, Custom Elements allow us to extend the functionality of existing HTML elements, creating hybrid-like elements that share functionality but also do extra cool stuff that standard HTML doesn’t do. The below shows the JavaScript we’d use to begin extending the button element into a new “mega button” element.

html-template-extend

 

HTML Imports

HTML imports are a way to include these Custom Elements in our web page from an external source. They follow the same syntax as referencing a CSS file (through the link tag) and can be used to import a single or multiple custom elements to minimise HTTP requests.

html-import

Polymer

The final thing to mention regarding Web Components – before we finally get our hands dirty with some code – is the Polymer library. Pushed heavily by the Google Chrome team, Polymer is a collection of Polyfill libraries, frameworks and APIs for using Web Components AND a pre-made UI widget library of Custom Elements, which is intended to ease the introduction of Web Components into the modern development cycle. We’ll use Polymer in our code example coming next.

Creating a Comment / Reply System

Web Components are a vast subject area – this post has only scratched the surface of them and has been written in a way so as to be as accessible as possible – so we’ll keep things easy and build a simple comment / reply system combining a couple of different ways to use Web Components. We’ll look at some of the pre-requisites and things to note and then you can take a look at the example created and hopefully create some cool stuff of your own. This example is meant just for newcomers looking to dip their toe into the Web Component ocean for the first time. You can take a look at the finished version: here.

Heads up: The code examples in this demo are all shown in images. You can grab a zip folder with all the files from here.
Heads up: Polymer requires you to run its files from a web server so make sure you have one to upload to or this demo won’t work!

Browser Support

The first thing to note is that Web Components are still in their infancy so browser support is sketchy. The following example will work fine in Chrome, Firefox and Opera but not, at time of writing, IE or Safari. You can check here http://caniuse.com/#search=web%20components to see the latest support details.

Directory Structure

Let’s begin by creating our working directory. For this we’ll simply create a folder for the JavaScript files and an “elements” folder for the HTML fragments we’ll import into our web page. Create an index.html file and we’re good to go.

web-components-example-directory-structure

Polymer Files

Since we’ll be using Polymer let’s start by grabbing the bits we need. We’re going to use two of Polymer’s JavaScript files – platform.js and polymer.js – which you can grab from their respective repositories on Github.

https://github.com/polymer/platform

https://github.com/polymer/polymer

Download the zip files from each and grab the following from the platform folder:

Platform.js

Platform.js.map

Put these into your js folder. Then do the same for the polymer folder:

Polymer.js

Polymer.js.map

Finally from the Polymer folder grab the polymer.html and pop that into your elements folder. Open this up in a text editor and change the src of the script to “../js/polymer.js” to set the path to our Polymer.js file.

Page Setup

Open the index page and reference the platform.js file near the top of your document head.

Heads up: Platform.js needs to be loaded into the DOM before anything else. This is important!

In between your body tags create some kind of holding div, add a heading and whatever else you want. I’ve kept mine simple:

Output:

web-components-example-output1

 

 

 

 

 

 

 

 

 

HTML:

web-components-example-html1

 

Creating a Polymer Element

Ok time to use Polymer. It has a very easy to pick up and play API so let’s start using it. Create a new HTML file and save it as comment-box.html. We’ll use Polymer to handle the input fields for our comment feature.

Firstly, we need to reference the Polymer.html file already in our elements folder using a HTML import statement. Put this at the top of the comment-box HTML.

web-components-example-import-tag

 

Heads up: As mentioned earlier any custom element created must contain a hyphen in its name.

A standard Polymer template looks something like this:

web-components-example-polymer-element

Heads up: There are a myriad of ways to create a Polymer element so be sure to take a look through their API guide here:  http://www.polymer-project.org/polymer.html to get an idea of what’s possible.

Data Binding

With Polymer, two way data binding between DOM and script is really easy. The Polymer method accepts a second argument – an object containing all of the attributes and functions tied to the custom element. These can be referenced and called in the markup through handlebar notation “{{ attr }}” or “{{ method }}.”

web-components-example-polymer-object

 

 

 

 

 

Two way Data Binding

The following is an example of two way data binding between a text input field in the DOM and an attribute and method in the Polymer element.

web-components-example-polymer-data-binding

 

To target an element within the template we use the $ sign. In the above we have a text input with an ID of “username” and so target it in the script through “this.$.username” in the checkLength method. All the method does is provide a real-time check on the length of the value of the username text field and prevents it from exceeding ten characters.

Heads up: Notice the event listener in the input field uses a hyphen and isn’t all one word or camel case. This is the syntax required so, for example, to register a click event on a button use “on-click,” not “onClick” or “onclick.”

Back to our comment-box element. Specify the Polymer element name to be “comment-box,” and add in any HTML you need. I’ve added a “p” tag to display the user name, a couple of text inputs (one for the username and one for the user’s avatar URL), a text area for the user’s comment and a submit button.

Style your HTML however you require in style tags just inside the opening template tag and add any functionality required through the Polymer object as shown above. My methods and properties are just to add a bit of basic validation and handle the submit click. Add any attributes to the attributes property within the Polymer-template tag.

HTML:

web-components-example-polymer-html

CSS:

web-components-example-polymer-css

 

 

 

 

 

 

 

 

 

 

Heads up: The “:host” CSS rule above refers to the custom element itself (the root element).

JS:

web-components-example-polymer-script

 

Adding the Polymer Element to the DOM

To use the Polymer element in our webpage all we need to do is add the tag to the HTML, for example <my-el></my-el>.

Using Template Tags without Polymer

Now we’ll link the Polymer element with a non-Polymer element. If you look through the script in the Polymer element you’ll see there is an “addReply” function called when the submit button is clicked. We’re going to use our next template tag to hold the code for a reply box template. Every time the submit comment button is clicked we’re going to clone the template reply and inject a reply box into the web page with the info entered into the comment-box text inputs and textarea.

web-components-example-non-polymer-template

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The template is given an ID so we can target it with JavaScript and there’s a bit of markup and styling. Place this template into your index.html file.

Cloning a Template with JavaScript

Injecting a reply into the DOM is really simple with JavaScript. We’ve wrapped this functionality inside a function which takes an image URL, the reply text and the username. The template tag is grabbed and its contents cloned. The values passed into the function are supplied to the HTML and then the reply markup is appended to the wrapper div that holds the page content.

web-components-example-non-polymer-javascript

 

And that’s it! All our markup is nicely self-contained, easy to manage and our web page is neat and tidy. What we’re left with is a simple but effective little Web Components comment / reply system that has hopefully introduced you to the subject and will give you enough of an insight to start making some cool Web Component based stuff of your own. Have fun!

View the finished version: here

By 2018, 42.4% of world’s population will be plugged into the internet, with around 3.6 bn people able to access it at least once a month.
RT : What is a ? It attaches rich photos, videos and media experiences to Tweets. http:/…