Skip to main content

Mobomo webinars-now on demand! | learn more.

web components This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!

The next release of Polymer, 0.8, is going to be a doozy. It's the first release on the "heading towards production" track and it's going to have some pretty massive differences from previous versions. So what exactly is new, and what's changing?

Note: This data was gathered primarily from reading the Polymer 0.8 Primer which is very, very extensive. I'm just hitting the highlights. Also note that any of this could change before the final release is cut.

A Tale of Three Polymers

Three Polymigos

One of the biggest changes in 0.8 is that there is no longer a single Polymer library. Instead, it's been broken into the three "layers" of polymer-micro, polymer-mini, and polymer. Why the change?

Remember, Polymer is really just a layer on top of the Web Components standards. Web Components are meant to be inter-operable with each other regardless of things like which framework was used to build them. Creating lighter-weight versions of Polymer makes it an easier choice for authors of reusable components by being less of an install burden. So which library should you use when?

  • polymer-micro has only a bare layer of sugar on top of the raw DOM APIs and a few niceties. You don't get any DOM template stamping facilities, so this is really meant for reusable elements with little to no DOM interaction (e.g. core-ajax).
  • polymer-mini layers some DOM control on top of micro and lets you do template stamping (but not template binding). Also gives you access to <content> and the new lightDOM and localDOM properties.
  • polymer is the closest thing to 0.5 (but still quite a bit different). It adds on attribute and property observation, template data binding, layout attributes, and more. This is what you're going to want to use if you're building a Polymer application.

Things You Can't Do Anymore

When you first look at 0.8 you may be a bit surprised. There's actually many things from 0.5 that are gone, vanished, kaput. It all has to do with production readiness. Polymer 0.8 is built to be lean, mean, and a foundation for shipping production code. Some of the more expensive (computationally and/or filesize-wise) features have been nixed. Watch the Polymer State of the Union talk for more detail there.

  • Elements can't inherit from custom elements anymore, only native. It's marked as a todo, but it's unclear if it's a before-0.8-launches todo.
  • Template binding is substantially less powerful than it was in Polymer 0.5, as is property observation. Everything's more explicit, and more is expected to happen in JS vs declared in templates.
  • Polymer will no longer ship with a spec-complete Shadow DOM polyfill. This was one of the biggest performance bottlenecks in non-Chrome browsers. The new polyfill implementation will be "Shady DOM" (details TBD).
  • Property observation does a bit less magic, you'll have to manually debounce some things.

Things That Are Different

In addition to removing some of the heavier features, there are also lots of structural changes to how you build custom elements. Here's a non-comprehensive list:

  • <polymer-element> is gone. Now you use the Polymer JS function to register your element, and the new dom-module element to specify templates.
  • You use the is property to declare the element name in a Polymer registration, e.g. Polymer({is: 'my-element'}).
  • Attribute bindings now work based on dash-case instead of camel-case (i.e. <my-element first-name="{{name}}"> binds to the firstName property. I am super happy about this, camel-case attributes are hideous.
  • You should now use the lightDOM and localDOM APIs to manipulate element DOM so that they are maintained properly.

Here, Bite Down on This

Hold on to your butts.

I'm not going to lie, if you're building stuff with Polymer the transition to 0.8 is going to hurt, bad. There's very little that won't need to be rewritten significantly (if not from scratch). That being said, this is a totally necessary transition.

As Matt McNulty said in his Polymer State of the Union, Polymer started as an experiment, and with 0.8 that experiment is over. It's time for Polymer to transition from a fun future-facing toy that we can dream about into a serious, performance-oriented tool we can use to ship real code.

By focusing on performance and footprint, the Polymer team is laying a practical foundation upon which much can be built. And yes, the changes are pretty drastic, but they're throwing them at us all at once. The plan is for the API to change minimally between 0.8 and 1.0, so (fingers crossed) this will be the biggest rewrite you ever have to do for Polymer.

Lingering Questions

I've been drinking the Web Components Kool-Aid since Polymer was first announced at Google I/O in 2013. The encapsulation and composability of custom elements is revolutionary for web apps. As we start looking at the road to production-ready Web Components, however, I still have a few questions:

  1. How will module loading shake out? With Mozilla backing away from HTML Imports and ES6 gaining popularity, it seems like there's a growing rift in how to do this properly. This is a key issue that needs to be sorted out; you shouldn't need a build step to do basic module loading for a web app.
  2. The DOM is big and unwieldy. Can we incorporate some of the gains of Virtual DOM tech into Polymer and/or the Web Components specs themselves? The concept of "Local DOM" or "Shadow DOM" gives us a clean encapsulation point, maybe soon we can get some of the benefits of React and its kin.
  3. When are Apple and Microsoft going to get fully on board with Web Components? The true promise of Polymer can't be realized until we have native browser support for the standards in all browsers.

Questions aside, I'm excited for Polymer 0.8 and we will continue to champion Web Components here at Divshot. Latest estimates put 0.8 landing sometime in March; I can't wait!

Categories
Author

web components This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!
I'm going to say something that (even in my own head) seems downright heretical. It's time to move past rigid separation of presentation and markup in web applications.

Many of us have been building things for the web long enough to remember the dark times, in the long-long-ago. Back when tables were used for layout, and the whole web looked, well, something like this.

As the web matured, we developers realized that six-deep nested tables weren't, perhaps, the best way to build things. And so began the age of the <div>. CSS allowed us to do everything (sort of, with a lot of hacky workarounds) we had done with tables, but now our markup could be gloriously free of style information. Gone were the <font> tags. Use of the style attribute became taboo, a sign of semantic weakness. And it was, if not good, at least better.

Somewhere around this time, however, a second important trend was brewing: the birth of the web application. Web sites that weren't just ways to display one's intense fandom for Doom II, but were ways to actually do things. As it turns out, browsers are quite the distribution mechanism.

Give and Take

True Fact: Square pegs do go in round holes if you hammer hard enough. That's how we used to get rounded corners.

As web applications grew more and more sophisticated, the contortions we applied using CSS to maintain semantics grew ever more bizarre. Floats within floats within relative-positioned negative-margin containers. Triple-nested <div> tags for that perfect sliding door rounded corner tab effect. The poor browsers, created to scroll top-to-bottom through a document's content, were being vigorously abused for the sake of better, more interactive applications.

Fortunately, browser standards change over time. Under the flag of HTML5 we got rounded corners, gradients, background image sizing, new tags like <section> and <header>. We even got stuff we didn't have to think about before, like media queries to make sites work on fast-growing mobile device categories. Our semantics were more semantic than ever, our buttons as glossy and round as we could ever care for them to be.

Building a proper interface or application layout, however, had scarcely gotten easier. Why is that? Because the semantics of HTML don't match those of application interfaces. Paragraphs, sections, articles, and lists are semantics that make sense in the context of a document, not an application.

Quibbling the Semantics of Semantic HTML

The document/application disconnect has given rise to frameworks like Bootstrap that provide much-desired UI widgets and layout constructs for building applications, not documents. You'll often see developers cringe at the inherent "wrongness" of "polluting" markup with Bootstrap classes. I posit that this is a reflexive and inappropriate reaction to what's really taking place.

Bootstrap, Foundation, and other similar projects are doing their best to equip developers with new semantics to describe interfaces. Interfaces are inherently visual; positioning, size, relative placement, and alignment are central semantic considerations for an interface's structure. There is no bright line between content and presentation because the presentation is the content.

Just look at modern JavaScript applications. Oftentimes the "document" content, the bit that was once central to the "semanticity" of a site, is JSON data loaded after the page loads and rendered to the interface using any of a number of client-side technologies. The HTML in these applications describes something fundamentally different from a rich text document.

Semantics are Dead, Long Live Semantics

UI and JavaScript frameworks provide stopgap measures to increase "app semanticity" in HTML, but they still function largely as hacks grafted onto an old, creaking system. Luckily for all of us, native solutions are finally beginning to arrive.

Flexbox solves many (if not most) of the fundamentally difficult aspects of building proper application layouts with HTML and CSS. It is a standard that gives us the power to do, and do it right.

Web Components offer us a real solution to the issue of app vs. content semantics. Namely, they let us define our own. If paragraphs and blockquotes don't suit your semantic requirements, how about user-profile or google-map? By freeing us from a set of predetermined tags, Web Components allow us to construct our own semantic context. They are going to change everything about how we build web applications.

The web is and will continue to be the best content distribution platform in existence. Nothing can rival its reach and simplicity. Now, after an extended awkward phase, the web seems finally ready to fight to ensure its spot as the best app distribution platform as well.

A Taste of the Future

What exactly does interface-semantic HTML look like? We can glimpse one possible future in Polymer, Google's Web Components polyfill and oh-so-much-more. It ships with a collection of layout attributes that allow developers to leverage Flexbox almost effortlessly.

Let's say I want my page to flow with a fixed header, then some content, then a footer at the bottom. Using layout attributes, it looks like this:

<body fullbleed vertical layout>   <header>My Header content here</header>   <section flex id="main">My main content</section>   <footer> </body> 

With no custom CSS and a declarative syntax that reads almost like English, the layout attributes offer simple semantics with a kind of "it just works" magic to them. Memorize a few keywords and you can build complex application layouts just about as fast as you can type.

I don't know whether Polymer's layout attributes are the best way forward. What I do know is that using them feels natural, almost addictive. HTML is remarkable for its ability to be declarative and compositional. Polymer offers one potential solution, but the biggest potential lies in the ability of developers everywhere to strike out in new directions, ignoring the constraints of the past. We're going to make some mistakes, we're going to take things too far; that's how progress is made!

What to Take Away

When building applications (as opposed to authoring documents), the structure of HTML should be judged not on how closely it adheres to semantics of content but to those of interface. Don't sacrifice the future on the altar of semantic purity. The next time that vein in your forehead starts throbbing at some "non-semantic" HTML, ask yourself: what are the true semantics at play?

It's early days for the next HTML revolution. I strongly encourage everyone to start learning, start experimenting, and start questioning the status quo. The best practices of the future haven't been discovered yet. Now's your chance to play a part in writing them. My suggestions:

  1. Play with Web Components. The Polymer site is probably the most comprehensive starting point for practical use today.
  2. Challenge your assumptions. Pretend you aren't scarred by years of battling HTML. What would your HTML look like if you defined the semantics?
  3. Share your results! No one has invented the best way to do just about anything with Web Components yet. The more people there are thinking, doing, and sharing, the faster we'll discover those as a community.

Let's all go forth and define the semantics of a new generation. The web platform, despite being more than 20 years old, is still in its infancy.

Update: Let's NOT Kill Accessibility

As was pointed out in the comments, many users of the web have needs other than just looking at things and clicking on them. This post was aimed at the dogmatism of "pure" markup and was in no way intended to encourage making the web less accessible. Here are a couple great links about keeping accessibility while building Web Components:

Thanks to @stommepoes, @aardrian, and @marcysutton for pointing out the omission and supplying the links! We should remember that putting users first isn't just a good idea, it's the standard!

Any questions, thoughts, ideas? Send 'em our way!

Categories
Author

polymer

This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!

There's so much new ground to cover with Web Components and Polymer that oftentimes some of the smaller conveniences are overlooked. Here are some of the cool things Polymer can do (or does for you) that you might not have noticed.

Built-In Element Methods

You may have used fire() to trigger custom events from a Polymer element, but that's not the only convenient little method that's available.

async(fn, inArgs, inTimeout) allows you to delay the execution of code (similar to setTimeout or requestAnimationFrame) while keeping this bound appropriately. It comes in handy for things like allowing an event to fully propagate before performing a dependent action.

// executes at the next micro-task checkpoint this.async(function() {   this.$.request.go(); }) 

job(jobName, fn, inTimeout) gives you the ability to limit how frequently an action is performed. Jobs are only executed after inTimeout milliseconds have passed without the same job being called again. You might have heard of this pattern as debounce. It's great for handling things like listening for noisy event streams like keystrokes or mouse movements.

// executes when it hasn't been called for 750ms this.job('keyup', function() {   this.fire('save'); }, 750); 

Layout Attributes

If you've browsed through Polymer examples and source, you might have come across attributes like layout, center, or flex sprinkled here and there. Polymer ships with declarative attributes that let you quickly and easily create complex layouts using CSS Flexbox.

Let's say I want to create a mobile-friendly layout with a header, footer, and content area.

<body fullbleed layout vertical>   <header>This will be at the top</header>   <main flex>This will fill available space</main>   <footer>This will be at the bottom</footer> </body> 

There's quite a bit to this, and the official documentation does a great job of laying it out.

Auto-Binding Templates

Polymer's template binding is powerful stuff, but what if you want to use it outside the context of an element's Shadow DOM? Well, then it's auto-binding to the rescue!

The auto-binding template is an extension of the <template> tag that automatically binds the element itself as the model.

{% raw %} <template id="greeter" is="auto-binding" repeat="{{name in names}}">   <p>Hello, {{name}}, how are you today?</p> </template> <script>   document.querySelector('#greeter').names = ["Alice", "Brenda"]; </script> {% endraw %} 

Because auto-binding templates can exist in the Light DOM (anywhere on the page, really) and don't depend on a user-defined custom element, they come in quite handy on occasion.

Attribute Reflection

Polymer makes it dead easy for attributes defined in the source code to configure properties on the DOM node, but did you know it goes both ways? By using a special form of published in your element definition, you can make it so that the attribute values change to match changing properties.

<polymer-element name="two-way">   <script>     Polymer('two-way', {       published: {         name: {           value: 'Bob',           reflect: true         }       }     });   </script> </polymer-element> 

If you were to use the above element in your page and changed the name property in JavaScript, the name attribute in the web inspector would change, too. Cool stuff!


Polymer is a library that keeps surprising me with how deep and well-designed it is (without even mentioning all of the core and paper custom elements!). It's way more than just a set of polyfills.

Have any Polymer hidden gems of your own you'd like to share? Let us know!

Categories
Author

This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!
Web Components are a collection of standards that allow folks to bundle markup and styles into custom HTML elements. They enable truly encapsulated and reusable components for the web and we just can't get enough of 'em at Divshot.

Thus, we'd like to share a little with you! Below are two screen-casts from our monthly Web Components Meetups. Enjoy.

Web Components, a Crash Course

We believe that web components are the future of web development. It's the front-end execution of compartmentalizing app architecture components.

In this video, I'll walk you through what web components are, how to use them, and why they matter, all in under 40 minutes.

Styling Web Components w/ Polymer

The beauty of Polymer components is how easy it is to style them and shipped as a single drop-in element. Jake Johnson walks you through the Shadow DOM and the included powerful tools for building a clean UI.

Got any questions, ideas, thoughts? Let us know!

Categories
Author

This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!

If you're diving into Polymer and the new world of Web Components, you may be wondering how to organize and structure your project. We don't have all the answers, but here's what we've found so far.

The structure of an application can be just as important for developer productivity as the frameworks and technologies upon which it's built. When something entirely new (like Polymer) comes along, it can take some time to settle into best practices. At Divshot we've been building small apps and a few larger ones using Polymer for the past year or so. This post summarizes what we've learned thus far about structuring apps.

Note: This isn't an introduction to Polymer but an exploration of best practices for those already using it. Try the official tutorial for a proper intro.

The Basic Structure

When we start building a Polymer app, we don't start with a complex generator toolchain. In fact, we don't start with a build process at all. It can make sense to add one in later depending on how large and complex your app gets, but Web Components are browser-native and it's nice to be able to take advantage of that!

The directory structure of our Polymer apps start something like this:

public/   bower_components/   components/   index.html .gitignore bower.json divshot.json README.md 

Pretty self-explanatory. The divshot.json is there for hosting on Divshot (of course), but also to use its custom routing to make index.html work for any URL during local development in true Single-Page App fashion.

Our .gitignore simply makes sure that we aren't checking in the contents of our Bower install:

/public/bower_components 

Bower is Your Friend

If you want to be productive, you absolutely need Bower. It's how the Polymer team is managing their own code, and you won't want to fight it.

So make sure you run bower init and create a .bowerrc file in your project's directory that points to the proper place. For many of our projects, the .bowerrc looks like:

{"directory":"public/bower_components"} 

If you plan to use Polymer UI Elements or Paper Elements, each comes with a "Kitchen Sink" package that installs all of its elements. While useful during development, you're unlikely to use every single one of them. There's a trick to make this easier: install the aggregate packages locally for development, but only add to bower.json the specific ones that you're using. So start with:

bower install Polymer/paper-elements bower install PolymerLabs/polymer-ui-elements 

And the first time you use one of the components (e.g. paper-ui-button) in your app, install it to your bower.json:

bower install --save Polymer/paper-ui-button 

Naming Elements

We've found it to be a helpful practice to come up with a short prefix that you apply to all of your application specific elements. This might just be app, but probably works better with your actual application name. For example, Polymer's Topeka example app prefixes its elements with topeka-.

Managing Element Dependencies

The public/components directory is where you'll be placing all of the custom elements that you build. In the beginning, this will likely be a simple list of .html files named after the elements, potentially with .css files to go along with them. A typical file will look like:

 <link rel="import" href="../bower_components/some-element/some-element.html"> <link rel="import" href="app-another-element.html">  <polymer-element name="app-my-element">   <template>     <link rel="stylesheet" href="app-my-element.css">        </template>   <script>     Polymer('app-my-element', {       // ...     });   </script> </polymer-element> 

Your dependencies will either come from inside the components directory or from your bower_components. It's your call whether to use absolute (e.g. /bower_components/some-element/some-element.html) or relative (e.g. ../bower_components/some-element/some-element.html) paths. Each has advantages and drawbacks, and we haven't settled on a clearly superior option yet.

You should always import all required dependencies at the top of an element. Even if you are using the same element in many files, you should have an import link at the top of each one. This way if you move things around, you won't accidentally break dependencies.

The only exception we've carved out to this rule is polymer.html which we directly import in the index.html file just after platform.js since every element we build requires it.

Alternative: Separate Elements Repository

Again referencing the Polymer teams' Topeka app, they to created a separate topeka-elements repository for all of their app's custom elements. While we can only speculate, it's likely that they did this so that they could install all the elements with Bower and consistently use relative path imports (e.g. ../some-element/some-element.html) in their code.

There are definitely advantages to this method, and it's one we're evaluating to see if it feels superior or more productive. The greatest challenge is in the need to constantly commit to two repositories that are tightly coupled as your application grows and changes.

Building Reusable Elements

Web Components are composable and reusable like nothing that has come before. In the course of making your app, you're likely to come up with a few elements that could easily be used for other purposes. The Polymer team has a great guide on creating reusable elements that we highly recommend, but it can be tough to work on one in the context of a larger app. Here's how we do it:

  1. Follow the linked guide above, but put the project folder for your new element inside public/bower_components.
  2. Initialize it as a separate git repository. Since its parent folder is ignored by git, you won't have a conflict in doing this.
  3. Publish your new element to GitHub. You don't have to register it with Bower just yet.
  4. Manually add a dependency to your bower.json for your new reusable component.

So long as you remember to push your changes up from your reusable component, your colleagues will be able to install it alongside all their other Bower dependencies.

Bundling Elements

One of the biggest "a ha!" moments we had while planning out structure was how to manage groups of related components. The answer was to utilize one of the web's oldest features: the directory index file!

As you begin to group elements together (maybe by feature, by function, whatever makes sense to you) you can create subdirectories in your public/components directory to house them. Then just create an index.html file that imports all of the grouped components. For example:

 <link rel="import" href="blog-post.html"> <link rel="import" href="blog-category.html"> <link rel="import" href="blog-comments.html"> 

Now when you want to be able to use these related elements, you can do so with a single import:

<link rel="import" href="components/blog/"> 

It's when you do things like this that you understand just how wonderfully well-designed the Web Components architecture is, and how well it fits into the existing HTML world.

Concatenation and Build Process

Most of our apps are still in the development phase and not quite ready for public consumption. As such, we don't have deep experience with trying to optimize Polymer apps for speed or network performance (yet).

Vulcanize is going to be a good place to start looking, though.


These are some of the tips and tricks that we've learned so far. Are you building Polymer apps? If so, what have you learned to be as productive as possible? Let us know!

Categories
Author
1
Subscribe to Web Components