Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

A Responsive Material Design App With Polymer Starter Kit

One upcoming technology that represents a big leap forward in making the web a mature application platform is web components1. From a high-level perspective, web components will enable better composability, reusability and interoperability of front-end web application elements by providing a common way to write components in HTML.

The goal of this article is to show you why this will be such an important step, by showing off what can be accomplished right now using Polymer2. Polymer is currently the most advanced and (self-proclaimed) production-ready library based on web components.

What Is Polymer? Link

Let’s get this out of the way: “Polymer is not a framework.” The team behind it strongly emphasized this at this year’s Google I/O talk about the 1.0 release. Polymer was announced at Google I/O 2013. Its purpose is to enable developers to work with web components and the four underlying low-level APIs — HTML imports3, shadow DOM4, HTML templates and custom elements5 — before the standards are finalized and implemented by all browser vendors.

This is accomplished by providing a set of polyfills that, well, “fake” the new API behavior where it is not yet implemented for the last two versions of all major browsers. Beyond these polyfills, Polymer also provides some syntactic sugar that makes working with web components a bit easier.

One year later, the project got a big boost at Google I/O 2014, as the team announced its ambitions to drive Polymer forward by providing an extensive library of prebuilt elements for developers, based on the material design guidelines.6 Now, one year later, the “production-ready” 1.0 version of Polymer was officially announced in the I/O 2015 keynote.7

So, let’s take a closer look at what all the fuss is about and what working with web components and Polymer feels like.

The Polymer Components Link

With version 1.0, the Polymer team announced different sets of element product lines8. These reusable building blocks are prebuilt for developers and show how web components will enable an ecosystem of modular building blocks.

  • Iron elements9
    These are utility elements that handle basic layouting and core functionality, without applying any complex visual styles.
  • Paper elements10
    These are a web component implementation of material design based on the iron element.
  • Google web components11
    These web components are wrappers for Google APIs and services. For example, there is an element for Google Maps, YouTube and Google Calendar.
  • Gold elements12
    These are special elements that can be used for e-commerce, such as credit-card input elements.
  • Neon elements13
    All fancy special effects fall under this label. Currently, only a web animations14 element is in there, which has some pretty cool demos15.
  • Platinum elements16
    This category is for components that enable complex web app functionality, such as push notifications.
  • Molecules17
    These elements are wrappers for other JavaScript libraries.

Beyond this official Polymer repository, you should check out Custom Elements18, a repository of even more elements. These elements are not necessarily based on Polymer but are still compatible thanks to the web component magic.

Example Application Link

Create Boilerplate Using Starter Kit Link

Enough with the high-level talk and overviews. How do we start developing with Polymer? Thankfully, the guys at Google have released19 a neat starter kit20 with version 1.0.

If you have Node.js, npm, Bower and Gulp installed, you can run the following command in the project directory to install all dependencies:

npm install -g gulp bower && npm install && bower install

For additional information on modern JavaScript tooling, check out the respective pages on npm21, Bower22 and Gulp23.

After installing the dependencies, you can run the kit with Gulp:

gulp serve

This command will build and serve the starter kit.

A Look at the Starter Kit Link

What we have here with the starter kit is a very basic application skeleton, with responsive layout, material design, routing functionality and offline caching via the service worker API.

Polymer starter kit24
Polymer starter kit. (View large version25)

Let’s take a closer look at what an application like this looks like under the hood in web component land. Look at the app/index.html file. In the head you can see that the script is included in the page:

<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>

This is the web component polyfill part of Polymer, which will become obsolete over time; Can I Use lists its current state26. At the time of writing, web components are supported natively 100% in Chrome and Opera and are currently behind a flag in Firefox.

A bit further down the line, you will find this part:

<link rel="import" href="elements/elements.html">

This is HTML imports in action. When you go further and open the elements/elements.html file, you will see that all of the elements used in the body of index.html are imported here. You could also directly import them into index.html, but the source file is a bit cleaner if you put them into their own .html file.

Now, let’s have a look at the actual markup of the application.

Structure an App With Web Components Link

Most importantly when looking at index.html, you will see a lot of custom elements, which are used to mark up the app. Here, you will see mostly elements from the iron-* and paper-* element libraries27. Custom elements need to be prefixed with this - notation to avoid collision with potential future base HTML elements.

You can see that the complete layout of the page is made up of paper and iron elements from the Polymer library:

<paper-drawer-panel>
   <!--Responsive sidebar drawer -->
   <paper-header-panel>
      <!-- Header of the drawer -->
      <paper-toolbar>
      </paper-toolbar>
      <!--Menu in the drawer -->
      <paper-menu>
      </paper-menu>
   </paper-header-panel>
   <!--Main content area -->
      <paper-header-panel>
         <!--Header of the main content -->
         <paper-toolbar>
         </paper-toolbar>
         <!--Main content -->
      <iron-pages>
      </iron-pages>
   </paper-header-panel>
</paper-drawer-panel>

This shows the very declarative and semantic way of structuring an app with web components. Imagine looking at the markup of such an application in a traditional web application; it would have hundreds of divs all over the place.

Web Components as APIs Link

Additionally, you have an example of the platinum-* elements that provide more complex functionality, such as facilitating the new service worker API. Service workers are another new standard API that enables you to create a background service in the browser that can handle caching, an offline experience for your web app and much more. It is not directly related to web components, so check out HTML5 Rocks’ article28 if you want to learn more about it. Similarly, the paper-toast element adds a notification toast functionality to the application. This shows the way web components can be used to capture more complex functionality and APIs.

Overall, the markup of the application shows the very declarative way of marking up an application by combining reusable elements. Notice that there is not a lot of additional JavaScript or CSS throughout the starter kit app. Most of the complex code is nicely encapsulated in the elements that were pulled in as dependencies.

Data Binding and Routing Link

You probably noticed that the application is wrapped in an HTML template tag:

<template is="dom-bind" id="app">
   …
</template>

This is done because Polymer uses HTML templates as context (as AngularJS does with the $scope, for example) for data binding.29 The is="dom-bind" shows the is attribute, which is a way to declare that some element is a custom element of the type provided as a value, while still inheriting from the tag it is placed on. So, this template tag gets treated as a dom-bind element, which is a custom element provided by Polymer that now inherits from the template element it was placed on. The dom-bind element here turns on Polymer’s binding capabilities in the template tag it was placed on.

AngularJS developers will probably spot this30 on first sight: The app is held together via data binding with the Mustache syntax. The connection between the paper-menu element and the iron-pages element is a great example of what can be done with this in a web component world.

The paper-menu element, which contains several anchor elements, is responsible for the state of the menu. The selected attribute is bound to the {{route}} variable.

<paper-menu class="list" attr-for-selected="data-route" selected="{{route}}" on-iron-select="onMenuSelect">
   …
</paper-menu>

The iron-pages element is responsible for filling the main content area with one of its child elements, depending on the state of the selected attribute. Here you can see that the {{route}} variable is being used to connect it with the menu state.

<iron-pages attr-for-selected="data-route" selected="{{route}}">
   …
</iron-pages>

This data-binding functionality is part of Polymer’s syntactic sugar and is not part of the basic web components standard.

Additionally, to bind the route correctly to a URL, a lightweight router is inside the elements/routing.html file.

page('/', function () {
   app.route = 'home';
});

page('/users', function () {
   app.route = 'users';
});

page('/users/:name', function (data) {
   app.route = 'user-info';
   app.params = data.params;
});

page('/contact', function () {
   app.route = 'contact';
});

// add #! before urls
page({
   hashbang: true
});

Here you can see how the route variable is accessed programmatically via app.route. Notice that the template element, used for data binding, has an ID of app. Inside the routing JavaScript code, the data inside the custom element is now available via its ID attribute value; that is why it can be accessed via app.*.

Creating Your Own Custom Elements Link

If you are interested in creating your own custom elements31 with Polymer, you will find the app/elements/my-greeting and app/elements/my-list elements that are defined and used in the starter kit application.

We won’t go in depth into how to create your own reusable elements, though, because that would probably require a whole article of its own.

Adding an Existing Custom Element Link

Let’s go beyond the boilerplate project and add another custom element. How about a Google Map?

Thankfully, there is already an element for that32 in Google’s product line. Adding it to your project is just one bower install away:

bower install --save GoogleWebComponents/google-map#^1.0.0

Now, you can include it with the imported elements in the app/elements/elements.html file:

<link rel="import" href="../bower_components/google-map/google-map.html">

Now that the element is imported, include it in your application — for example, on the “Contact“ screen:

(…)
<section data-route="contact">
   <paper-material elevation="1">
      <h2 class="paper-font-display2">Contact</h2>
      <p>This is the contact section</p>
   </paper-material>
   <paper-material elevation="1">
      <google-map latitude="37.77493" longitude="-122.41942"></google-map>
   </paper-material>
</section>
(…)

Some additional CSS is still needed in the app/styles/main.css file to set the display height of the map.

(…)
google-map {
   height: 600px;
}
(…)

Voila! You’ve just added a Google Map to your application, without tinkering with any iframe or initializing a JavaScript library.

Adding a Google Map without tinkering with any iframe or initializing a JavaScript library33
Adding a Google Map without tinkering with any iframe or initializing a JavaScript library. (View large version34)

This neatly showcases how developers can take advantage of web components to reuse elements without having to create the same boilerplate or reinvent the wheel. The standard method of adding a Google Map35 to an app without web components is cumbersome by contrast.

Adding a Non-Polymer Custom Element Link

Another thing we might want on the web page is an animated GIF. Go to Custom Elements36 and find the x-gif element37, which promises smooth GIF playback. Unfortunately, it is not based on Polymer. But no problem! It can be added like any other web component.

Again, let’s do a quick bower install to fetch the x-gif component:

bower install --save x-gif

Add it to your app/elements/elements.html imports list:

<link rel="import" href="../bower_components/google-map/google-map.html">
<link rel="import" href="../bower_components/x-gif/dist/x-gif.html">

Put your favorite GIF in app/images/epic.gif, and add it to the home screen using the x-gif tag:

<section data-route="home">
   <paper-material elevation="1">
      <my-greeting></my-greeting>

      <p class="paper-font-subhead">You now have:</p>
      <my-list></my-list>

      <x-gif src="images/epic.gif"></x-gif>

      <p class="paper-font-body2">Looking for more web app layouts? Check out our <a href="https://github.com/PolymerElements/app-layout-templates">layouts</a> collection. You can also <a href="http://polymerelements.github.io/app-layout-templates/">preview</a> them live.</p>
   </paper-material>
</section>

Mind-blowing:

Using the x-gif web component38
Using the the x-gif web component. (View large version39)

Just remember that the x-gif web component has nothing to do with the Polymer library; it is built using the vanilla web components APIs. This really shows the interoperability of web component-based elements. Now, think about how popular frameworks like AngularJS 2.040 and Google Web Toolkit 3.041 will be based on web components in future versions and how much more interoperable frameworks will be in future. By the way, Mozilla is also working on a web component-based library, Bricks42, which is pretty far along in development.

Conclusion Link

We’ve seen now what working with web components in Polymer 1.0 looks like, using the starter kit as a foundation. And we’ve seen the declarative and boilerplate-free way to combine reusable elements, elements that interoperate without necessarily having been developed with the same libraries or frameworks.

I am really excited about web components because they mark a huge step in the advancement of the web and its transformation into a fully capable application distribution platform, without the quirky hacks and framework silos of the past.

Resources Link

Elements Link
Videos Link

(al, ml, rb, jb)

Footnotes Link

  1. 1 https://www.smashingmagazine.com/2014/03/04/introduction-to-custom-e=lements/
  2. 2 https://www.polymer-project.org/1.0/
  3. 3 http://webcomponents.org/articles/introduction-to-html-imports/
  4. 4 http://webcomponents.org/polyfills/shadow-dom/
  5. 5 http://webcomponents.org/articles/introduction-to-custom-elements/
  6. 6 http://google.com/design/
  7. 7 https://www.youtube.com/watch?v=fD2As5RmM8Q
  8. 8 https://elements.polymer-project.org/
  9. 9 https://elements.polymer-project.org/browse?package=iron-elements
  10. 10 https://elements.polymer-project.org/browse?package=paper-elements
  11. 11 https://elements.polymer-project.org/browse?package=google-web-components
  12. 12 https://elements.polymer-project.org/browse?package=gold-elements
  13. 13 https://elements.polymer-project.org/browse?package=neon-elements
  14. 14 https://w3c.github.io/web-animations/
  15. 15 https://github.com/PolymerElements/neon-animation#demos
  16. 16 https://elements.polymer-project.org/browse?package=platinum-elements
  17. 17 https://elements.polymer-project.org/browse?package=molecules
  18. 18 https://customelements.io/
  19. 19 https://developers.google.com/web/tools/polymer-starter-kit/
  20. 20 https://github.com/polymerelements/polymer-starter-kit
  21. 21 https://www.npmjs.com/
  22. 22 http://bower.io/
  23. 23 http://gulpjs.com/
  24. 24 https://www.smashingmagazine.com/wp-content/uploads/2015/08/01-starter-kit-opt.png
  25. 25 https://www.smashingmagazine.com/wp-content/uploads/2015/08/01-starter-kit-opt.png
  26. 26 http://caniuse.com/#search=web%20components
  27. 27 http://elements.polymer-project.org
  28. 28 http://www.html5rocks.com/en/tutorials/service-worker/introduction/
  29. 29 https://www.polymer-project.org/1.0/docs/devguide/data-binding.html
  30. 30 https://www.polymer-project.org/1.0/docs/devguide/data-binding.html
  31. 31 https://www.polymer-project.org/1.0/docs/devguide/data-binding.html
  32. 32 https://elements.polymer-project.org/elements/google-map
  33. 33 https://www.smashingmagazine.com/wp-content/uploads/2015/08/02-maps-screenshot-opt.png
  34. 34 https://www.smashingmagazine.com/wp-content/uploads/2015/08/02-maps-screenshot-opt.png
  35. 35 https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
  36. 36 http://customelements.io
  37. 37 https://github.com/geelen/x-gif/
  38. 38 https://www.smashingmagazine.com/wp-content/uploads/2015/08/03-mindblowing-opt.png
  39. 39 https://www.smashingmagazine.com/wp-content/uploads/2015/08/03-mindblowing-opt.png
  40. 40 https://angular.io/
  41. 41 http://www.gwtproject.org/
  42. 42 http://brick.mozilla.io/
  43. 43 https://developers.google.com/web/tools/polymer-starter-kit
  44. 44 http://polymerelements.github.io/app-layout-templates
  45. 45 https://github.com/PolymerElements/app-layout-templates
  46. 46 https://elements.polymer-project.org
  47. 47 https://customelements.io
  48. 48 https://www.youtube.com/watch?v=fD2As5RmM8Q
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Advertisement

Sebastian is a web and technology enthusiast from Germany who got heavily into JavaScript in the last couple of years. Besides some freelance work his main occupation is being the technical co-founder of the start-up snapADDY. In his spare time he co-organizes the local FrankenJS JavaScript user group in Nuremberg

  1. 1

    Why Polymer, WebComponents are all about supporting native features. Why not write an article actually explaining/showing how to use it natively?

    0
  2. 4

    None of the YouTube video links seem to be working.

    0
    • 5

      Markus Seyfferth

      October 13, 2015 10:15 pm

      Thanks for the heads-up Bill! Very unfortunate indeed (someone decided to remove the videos), so I took out those links.

      0
  3. 6

    Cristian Jujea

    October 13, 2015 10:22 pm

    I’m a web app product manager and an enthusiast of new web and mobile technologies. But with the headaches I get from cross-browsers compatibility issues, adaptive, responsive, interaction design, etc. etc. etc., I beg for very practical presentations of very practical technologies.

    It’s all about the end user – any developer actually works for the end user.
    Yet, User-Centered Design – which is the most practical project management type – is barely considered by developers and almost never mentioned in articles about how to apply new technologies.

    0
    • 7

      You just don’t get it. This is so exiting, you will be able to do sliders that aren’t but :)

      1
  4. 8

    Mike Bunce (bunce.space)

    October 13, 2015 11:35 pm

    We have just started using web components here at work, and they look like a great streamlined approach to include dynamic components that are shared across applications. Polymer provides a great way of having browser compatibility before browsers have formally implemented the functionality – love it!

    1
  5. 9

    npm WARN ENOENT ENOENT: no such file or directory, open ‘/Users/saerts2013/Sites/_test/web-components/package.json’
    npm WARN EPACKAGEJSON /Users/saerts2013/Sites/_test/web-components No description
    npm WARN EPACKAGEJSON /Users/saerts2013/Sites/_test/web-components No repository field.
    npm WARN EPACKAGEJSON /Users/saerts2013/Sites/_test/web-components No README data
    npm WARN EPACKAGEJSON /Users/saerts2013/Sites/_test/web-components No license field.
    npm ERR! code 1

    ➜ web-components gulp serve
    [10:46:02] No gulpfile found

    -3
  6. 10

    In what universe is that a good thing ?
    I will spend more time learning this new kind of coding for doing the exact same thing.
    I want a google map inside a page ?
    I asset my javascript / css.
    I copy & paste my code.
    Done.

    I dont have to renember your own tag, to use bower with this line etc..

    2
    • 11

      I see your point David, and it is the pragmatic approach today and what I will continue to do for some time. But I must say I love the concept of a composable UI that rises above individual frameworks, and turns other components into blackboxes that can be added and configured right in the HTML (no-JS needed for the conventional setup of a component). A handy UI metaphor could be a google/npm/etc. search away, and tooling (think text editor with autocomplete) could be made responsible for telling me what elements and attributes are available to be set and of those which are required to be set. So learning and incorporating someone else’s blackbox into my project could be fairly painless in the near future.

      Having said all that, the idea of importing AngularJS into my project that is not using it just so that I can use a component that depends on AngularJS sounds a bit far-fetched. Frameworks will still matter.

      0
  7. 12

    Sooo…. Beyond the overhead of shipping the polyfills across the network, there’s also the time it takes for the browser to parse and interpret the JavaScript code. Official statement is that they don’t do performance testing and optimizations. Let’s talk browser support and known issues then :)

    Browser Support:
    – IE11+
    – Chrome
    – Firefox
    – Safari 7+
    – Chrome Android
    – Mobile Safari

    Known Issues:
    – Custom element’s constructor property is unreliable
    – Contenteditable elements do not trigger MutationObserver
    – ShadowCSS: :host-context(…):host(…) doesn’t work
    – execCommand isn’t supported under Shadow DOM

    All of you – check this link before considering usage:
    https://github.com/Polymer/platform-dev/blob/fe5427b747e5bca3dde9ba891cb33d279faff3f9/src/ShadowCSS.js#L10-123

    2
  8. 13

    victor castrejon

    October 14, 2015 8:43 pm

    Nice article, I really like where polymer is going.

    * BTW there is an extra = at the end of the ‘HTML templates’ link in the second paragraph

    0
  9. 14

    Today as the online shopping grows in popularity more people are turning to online shopping for all their needs. Send Diwali Gifts to India Same Day which is filled with your good wishes. Send Deepavali Sweets to India and make your dear ones feel at the top-of-the world..

    -16
  10. 15

    What I understand is that Polymer is what I call a typical Google product.

    “Its purpose is to enable developers to work with web components (…) before the standards are finalized”
    => let’s adopt that new fancy thing before it’s mature enough.

    ““Polymer is not a framework.” The team behind it strongly emphasized this at this year’s Google I/O talk about the 1.0 release”
    OK.

    “Polymer also provides some syntactic sugar that makes working with web components a bit easier.”
    So it’s not just a polyfill but also something else. But it’s not a framework.

    “One year later, the project got a big boost at Google I/O 2014, as the team announced its ambitions to drive Polymer forward by providing an extensive library of prebuilt elements”
    Still not a framework ?

    “based on the material design guidelines”
    Now it’s not just a polyfill for old browsers which don’t support a finalized standard : it’s a way to spread the Google look’n’feel with components.

    “Google web components. These web components are wrappers for Google APIs and services. For example, there is an element for Google Maps, YouTube and Google Calendar.”
    Oh even better, now it’s a framework to spread not only the Google look’n’feel across the web, but a way to promote Google services.

    What was supposed to be a purely technical polyfill turns out to be one more tool to Googlify the web. No thanks.

    1
    • 16

      Kit Brown-Watts

      October 27, 2015 1:00 am

      The entire project is open source and no one is forcing anyone to Googlefy the web. You can use the technology to design and develop whatever you want! Obviously because the team is employed by Google, some of the initial components to be created will be Google-focused, but would you not do the exact same if you were running the team?

      Material Design is based on a great deal of human computer interaction research, everything from the line spacing to the border radius is meant to optimise readability and usability – and even then there’s absolutely nothing locking you in to using it. The entire point of Web Components and Polymer is to make it easier to encapsulate whatever look and feel you want into a standalone html element that others can just use, unlike traditional ui from frameworks.

      It’s easy to sit on the sidelines and criticise – but if you have a better vision then go ahead and do it! This is the whole point.

      6
  11. 17

    Will take decades to all browsers support that, and will take more to text editors be able to auto complete and give you coding performance, and then another web shit will be created.

    Even HTML5 is not completely done yet. weirdo…

    -7
  12. 19

    Current browser compatibility, and any speed concerns aside, I think Polymer (and Web Components) represents a change for the better in web development.

    The “microservice” style of building components, and applications, is ideal in my mind. It’s already becoming the preferred style of developing backend api’s, why not use the same methods on the front end. When everything is decoupled (for the most part), changing a small part of the app is breeze. Polymer, for me, is sooo much nicer to use than Angular 1.x.

    There are issues though, of course. 1.0 hasn’t even been out for 6 months yet. So, people need to have a little patience with it. Eric Bidelman from the core team has a really great talk on performance from their recent Polymer Summit (all the lectures are on youtube).

    1

↑ Back to top