Polymer and the Shadow DOM
It's 2014, and "component-based architecture" is the talk of the town. While React is gaining traction, the W3C's Web Components standards are the official way forward. Google's Polymer library is the leading polyfill and sugar layer for these specs. The most powerful (and misunderstood) part? Shadow DOM.
The Problem with Global Scope
In 2014, we're all suffering from "CSS Leakage." You change a class in one part of your app, and it breaks a button in another. Shadow DOM fixes this by providing a scoped DOM subtree.
Creating a Shadow Root
With the raw API, it looks like this:
var host = document.querySelector('#host');
var root = host.createShadowRoot(); // Web Components v0 syntax
root.innerHTML = '<style>h1 { color: red; }</style><h1>Shadow Hello!</h1>';
Even if you have a global style that says h1 { color: blue; }, the header inside the shadow root will stay red. This is true encapsulation.
The Polymer Way
Polymer makes this much more declarative using HTML Imports (another emerging standard).
<link rel="import" href="polymer.html">
<polymer-element name="my-counter" attributes="count">
<template>
<style>
:host { display: block; border: 1px solid #ccc; }
span { font-weight: bold; }
</style>
<div>Count: <span>{{count}}</span></div>
<button on-click="{{increment}}">Increment</button>
</template>
<script>
Polymer('my-counter', {
count: 0,
increment: function() {
this.count++;
}
});
</script>
</polymer-element>
Content Projection with <content>
How do you pass data from the "Light DOM" into the "Shadow DOM"? In 2014, we use the <content> tag and the select attribute.
<!-- Inside the template -->
<header><content select="h1"></content></header>
<main><content></content></main>
Web Components represent a shift from "libraries" to "platform features." Polymer is just the bridge to that future.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development