Google Polymer and web components tutorial

pokemon web audio

I started working with polymer, to get a feel for what it was all about. Here’s how Google describes it:

Web Components usher in a new era of web development based on encapsulated and interoperable custom elements that extend HTML itself. Built atop these new standards, Polymer makes it easier and faster to create anything from a button to a complete application across desktop, mobile, and beyond.

Here are the four specifications that form web components:

  1. Custom Elements
    1. enabling the author to define and use new types of DOM elements in a document.
    2. Status.Modern.ie: Under consideration
  2. Shadow DOM
    1. combining multiple DOM trees into one hierarchy and how these trees interact with each other within a document, thus enabling better composition of the DOM.
    2. Status.Modern.ie: Under consideration
  3. HTML Imports
    1. include and reuse HTML documents in other HTML documents.
    2. Status.Modern.ie: Under consideration
  4. HTML Templates
    1. declare fragments of HTML that can be cloned and inserted in the document by script.
    2. Status.Modern.ie: Under consideration

Why is this useful?

Ever add framework or library to your web project, only to find that the CSS overwrote some of your styles? Now, you’ve got to edit the order that the styles are loaded, as well as make changes to your own code. It’s time consuming and frustrating, to say the least.

Shadow DOM offers reusable components. All of your CSS and markup are scoped to the host element, so the styles defined inside of the Shadow Root (your polymer element) will not affect the rest of the page.  You can find an excellent overview of how it workw at WebComponents.com.

What about Browser Support?

Image courtesy of http://webcomponents.org/

Image courtesy of http://webcomponents.org/

You can always head to status.modern.ie to see what the current support looks like for Internet Explorer. Microsoft updates the site frequently to illustrate what is coming down the pipeline and what developers are saying about it.

Alternatively, caniuse.com is a great resource for seeing what support looks like across the board, including mobile browsers. This site however, does not display whether or not the browser in question currently has the technology in consideration or under development.

Are there any competiting technologies?

Firefox and Chrome have been duking it out for some time now, in terms of support for these various web components. Firefox has their own technologiy, X-tag, which only depends on Custom Elements, and gives the developer the ability to opt-in for Shadow DOM. Here is a great comparison of the two.

Shadow DOM support

Finding a good starting point

To get a feel for how polymer works, I first wanted to use some web components that other people had made. In this case I started by browsing the CustomElements.io page in search of some interesting things for me to learn from and use. The x-pokemon web component  and voice-elements web component immediately grabbed my attention.
With those two, I could easily parse the Pokemon database and draw the images of Pokemon on screen, then use voice elements to say the name of the pokemon!

After tinkering with those, I decided that it was time for me to go off on my own and create my first web component.

Creating my own component

Polymer Designer is a fantastic browser-based tool made by Google, which allows your to design a paper element inside of the browser with their drag-and-drop GUI. Even better — it spits out the code for you! This proved to be invaluable, when I was learning how polymer worked.

I wanted to design something simple, so I created a container to hold three radial buttons; one button for each language selection. Users now have the ability to select a radial button associated with a language (en-EN, en-GB, and es-ES), which would in turn be tied into the audio web component and change the accent.

radial buttons

The “Change the accent” text isn’t part of the polymer element. It’s part of the HTML of the page, but I wanted to include it in this snipper so that you understoof what these buttons do

After laying out my content, here is what designer spit out:

*I’ve added the comments 

Paper elements

You may also notice that these elements make use of paper. It took me a bit to understand what paper was exactly, becuase if you try to Google it, you likely won’t get what you expect.  To add this element to my project, I also needed to add Google’s paper elements. As I understand it, paper elements are Google’s material design brought to the web. To install paper elements, run the following in your command line:

bower install Polymer/core-elements --save

 

  Note for Visual Studio users: I’ve found that Bower can throw errors when trying to use the command line tools within Visual Studio. A post on stack overflow clarifed that I should use a separate command line tool, such as powershell, to install Bower packages. Once I did that, everything worked well. I changed directories by with cd “name of directory where my web project is” to have power shell pointed towards my project, and then I could use all of the Bower commands to install components. Ex: cd C:UsersDaveDocumentsProjectsPokemon-WebAudio

 

  Adding JavaScript to the polymer element

I had my HTML and CSS complete, but I needed to start wiring up my JavaScript. It took me a bit of time to understand how polymer handles its JavaScript, as they have a ton of documentation on the subject, but not many pracitcal examples. Note, they have many examples, but it basically turns to “hello world” without any substance. They go over JavaScript in detail in the API developer guide, but it was stack overflow which really proved to be useful here. For example, I’m still not exactly sure oh how entering code into

 Polymer{()}

is different from entering it in the <script> tag.  Below is the JavaScript that I use in my polymer element:

The only reason I knew that wrapping my attributes in an IFFE made them global is because that was something on stack overflow. WIthout that, I wasn’t sure of how to access them from outside of the polymer element.

Most of the methods here are not being used — I simply wrote them as a way to test things out and debug as I was moving along. For example, I illustrate how to return the first element in my polymer element, which is essentially encapsulated hidden from the browser via Shadow DOM. That syntax looks like:

this.$.paper_radio_group.querySelector(#paper_radio_btn_en-US");

Sure, the syntax is kind of funky, in that you need to use the this keyword followed by the $ symbol, and then the name of the top level object, which then exposes the ID of the object you are trying to actually grab.

 How does it all work?

Now that I understood how polymer elements work, I was able to dissect the work of others, and now create my own, it was time to put it all together.

I started with HTML5 Boilerplate, which I cannot recommend enough, as it provides an excellent starting point for most web projects. Out of the box it incldues libraries such as jQuery, Modernizr, Bootstrap, and Normalize.css, among many others.

Next, I use the Bower command line to add the x-pokemon and Web Speech components.

Inside of index.html

Opening this page, we see that I have some text, followed by my radial button element that I created in polymer.
index.html has no clue of what that tag is though, at least until I import it at the botton of the page. Therefore, add this line to the botton of index.html:

 <link rel="import" href="bower_components/radial-buttons/x-radial-buttons.html">

I repeated these steps for the two components listed above.

Tying the JavaScript together

With our HTML complete, we now need to wire everything up. In main.js I have two (2) event listeners.

One listens for when the text has changed in the input form and performs two operations. After each character, the pokemon component (with Angular) quickly searches the pokemon database to see if such a pokemon exists, and if it does, draws it to the screen. In addition, this also sets the text inside of the audio web component. Here’s the code:
The other listens for when the submit button is pressed, and when it is, calls the function sayTheName. We prevent the default functionalty of the submit button from firing, which would actually submit a form on the page. Instead, we tell the audio component to speak (using the text we set in the previous listener).

That’s all fine and good, but we need to add in my functionality, though.

I have a function called changeAccent, which grabs the current accent from the radialButtons I created, then does a console.log to state what the current accent is, then illlustrate what it is about to be changed into. The next line called the audio web component, finds the “accent” attribute in the HTML tag, and sets it to the new accent we passed in from the radial buttons I created.

Final Notes on the project

This currently only works in Chrome, as it not only supports the the four items listen above which make up Web Components, but it also has support for Web Speech, which is currently under consideration in IE and experimental in Firefox at the moment.  I’m working on creating a side project which has this Pokemon web app, but removes the dependency on Web Speech. I should have that up soon.

Introduced late in 2012, The Web Speech API, allows for speech input and text-to-speech output features in a web browser.  Moreover, the API takes care of the privacy of the users. For example, the user must explicitly grant permission bBefore allowing the website to access the voice via microphone. This Site Point article explains it well.

Polymer fills in everything else that was missing, which is why you see that my paper elements (radial buttons) and the other Shadom DOM objects all appear on screen. Unfortuantely, Web Speech is not part of Web Components.

Web Speech CanIUse

In conclusion

That’s all there is to it, really. Now you’ve seen how I learned about polymer, added my own element, and created a simple project. I plan on cleaning up the UI next and digging into Google’s paper elements a bit more to create a cleaner design. I also wrote a tutorial on how to access member functions in polymer-elements can be found here.

I’ve commented all of the code pretty well, so take a look at how I’ve put it all together and read through the comments. Any questions, feel free to ask.

Also, if you’d like to host your next polymer project in the cloud, reach out to me about BizSpark  and we’ll get you signed up for a free account.

-----------------------


subscribe-to-youtube

7 thoughts on “Google Polymer and web components tutorial

  1. Interested in the Polymer vs X-tag comparison, but the link appears to be broken. Also, what are your thoughts on using Polymer in an ASP.net MVC project?

    • Thanks for pointing that out! I’ve added the correct link.

      I really haven’t used x-tag, so I can’t get an honest appraisal of it. I think that link provides much more information and context than I could, though.

  2. Great tutorial with really good insights into the gaps/problems you experienced. I may have overlooked the link to the live project, is it hosted anywhere for us to see? Also, I was interested in seeing a gallery/catalog of various things that were created with polymer. Is there such a thing? I was also curious if you could open a project from the online “designer” tool. It doesnt appear there is currently an option, but I didnt know if there is a workaround. Thanks!

    • Sure thing, you can find the live project here: http://pokemonwebaudio.azurewebsites.net/

      It will only work in Chrome right now, because they are the only browser to implement the speech audio API. I need to finish the second version of this project, which does not use that API, so that this will work in other browsers.

      The best catalog I’ve seen for finding what people have done with Polymer is here: http://builtwithpolymer.org/

      and there was another one, where I found the x-pokemon project, but I can’t seem to find that site anymore…

      I don’t believe that there is a way to open a project from the designer tool, unfortunately.

  3. I am no coder. I am really interested in using the online design tool (and I have) – but I cannot preview or save my project because I do not know how to configure the github token – and I cant find a simple video or other explanation on how to do it. Ive looked at the available info and cant figure out how to implement it. Can you point me to something that is easy to follow pls? https://goo.gl/2q64z8

    • Why does it say that you need a GitHub token?

      When I use the online tool, it gives me the code if I hit the “Toggle code / design” button in the top left corner. I just copy that code and save it as a text file. This way I can put it in my projects.

      I’m looking through this as well, and when I hit “save” it asks for a GitHub token as well. I’d avoid going this route for now, as I am not sure of how to acquire this either.

Leave a Reply to davidvoyles Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.