Writing modular frontend components in 2013

Backend developers use encapsulation to apart and organize formula to forestall conflicts, nonetheless what can frontend developers use in a browser to grasp a same end?


As we build web applications that turn some-more and some-more complex, we contingency scale a growth practices to hoop an augmenting volume of technical debt. The formula we write should be modular, reusable and encapsulated to forestall firmly joined applications. Monoliths are time-consuming and unwieldy for any developer to work on.

As frontend developers, we’ve been regulating intent constructor and procedure patterns to keep JavaScript formula docile and encapsulated. But it’s about time we had some proceed of encapsulating portions of a DOM so we don’t have fixing collisions and unintended interactions.

Browser vendors are operative on APIs that concede us to emanate improved encapsulated components in a browser. If you’re building an focus with a lot of facilities in a singular page, or an focus relying on a lot of third celebration code, afterwards encapsulation can’t come shortly adequate for you.

What’s a component?

“The best thing that can be pronounced of program is that it is too small.” – James Halliday, from Code Collage during JSConfEU 2012

A component, for a functions here, is a little square of program that does one thing well. A member should embody all a suitable pieces it needs to do a job, no some-more and no less. We welcome minimalism as most as we can for any member so prolonged as we don’t scapegoat a elementary poise and structure. A frontend member should enclose all a HTML, CSS, and JavaScript required for a barebones doing of whatever it’s ostensible to do.

You competence be seeking yourself since a stream proceed regulating jQuery UI or ExtJS isn’t enough. These are modular member libraries that have already solved a need for these reusable formula building blocks. Unfortunately, they’re lacking a one thing we need to forestall problems like namespace collisions and ungainly CSS specificity as we broach some-more and some-more complexity into a application.

These methods inject formula into a page where needed, nonetheless that formula is not encapsulated. Many well-written libraries have been implemented in such a proceed that it’s not something we have had to worry about. But they’re not foolproof. Introducing encapsulation in a DOM could make things even better.

Encapsulation: a review

Code-wise, an intent is encapsulated when it exposes a singular open interface to correlate with other code, while a information and doing sum are private.

The one time we get to use hulk robots as a technical metaphor

Anyone remember a Mighty Morphin’ Power Rangers? They were masked superheroes that battled opposite immorality army with hulk armoured robots. Each Power Ranger had a possess drudge with a possess middle workings; a possess commander and a possess middle state that usually he or she knew about. To broach a finishing blow to an enemy, a Power Rangers would mix all a robots into a most incomparable drudge called a Megazord.

When coupled, a member robots could interface effectively by their pilots around a common authority hire nonetheless exposing a middle workings of any drudge to any other. Each ranger’s drudge could be pronounced to be encapsulated; any one was a member of a larger whole called Megazord that would flog some critical butt.

The indicate in all this

In sequence to write easy-to-maintain applications, a frontend formula should be damaged down into little components that do usually one little underline unequivocally well. Beyond that, we wish to be means to use a formula in a page nonetheless risking namespace collisions or CSS selector trampling. In sequence to build strong applications, we wish a components to be encapsulated, and so distant we haven’t had really good ways of doing this with a DOM in a browser. Let’s mangle down a options accessible for us as we start 2013.


Until recently, a usually truly encapsulated elements that developers had during a ordering were iframes. There are a lot of problems with regulating iframes to make components: they don’t enhance to fit content, visible decorations of a essence can’t overlie a support – a list can go on. Also, iframes are slow.

The criticism program combined by Disqus uses iframes to arrangement comments for a given document. If we pointer in to Disqus in a iframe, a primogenitor website can't have entrance to any of your record information. Your handshake to leave a criticism is between we and Disqus only, and has zero to do with a primogenitor web page that you’re withdrawal a criticism on. Go check a page with Disqus, and you’ll see.


  • Good for situations where we wish some-more confidence for your users
  • Implemented in all fast browser channels
  • Prevents JavaScript conflicts between scripts in your categorical DOM and iframe/component
  • Can bucket calm from a opposite domain than your focus is hosted on


  • Don’t enhance to fit content
  • Hyperlinks can usually navigate inside iframe, not primogenitor context
  • Visual emblem of elements within a iframe can’t overlie iframe boundary
  • IFrames are slow. One in a page, and you’re fine, nonetheless any some-more than that spells trouble

IFrames can offer a grade of confidence and concede for loading off-domain calm with ease, nonetheless over that, vanilla iframes are not going to be my initial choice for creation components.

Seamless iframes

When we started exploring deeper into intensity methods of DOM encapsulation, we became assured that newer methods were going to trump iframes and that iframes would eventually swab divided into contingent deprecation and obscurity.

Then a seamless charge finished adult on my radar and I’ve had to rethink my position. It seems like iframes competence hang around as a means to an finish in this problem domain.

This charge changes how a iframe behaves in several vital ways. CSS manners can cascade by a iframe, hyperlinks will automatically navigate a primogenitor DOM context, and a iframe will automatically resize itself to fit a bounding box of content.

Sounds great, right? Let’s boat it on prolongation right away! Ah, solely that this charge is so new that no fast browser channel has implemented it. However, if we squeeze a duplicate of Chrome Canary, we can play with it. It competence be a while before we see this charge in a fast channel, nonetheless keep your eyes open for it.


  • Great if we wish to inline some functionality and wish a facilities and styles of a primogenitor range to trifle in
  • HTML links duty in primogenitor context
  • Resizable, inline inlet creates for stretchable styling


  • Not implemented in any fast browser channel. You contingency have Chrome Canary in sequence to experiment.
  • Getting poise usually like it is probable nonetheless could take we some time to get right

Web components

While a reinvention of a iframe has been happening, a new challenger has seemed watchful during a gates: web components. The name sounds generic, nonetheless in this context it refers to a span of W3C specifications to standardize browser poise for encapsulated components regulating Shadow DOM and Custom Elements.

Shadow DOM

The new Shadow DOM API gives developers a ability to insert a fully-fledged DOM inside of a horde element. You should consider of this fundamentally like there is a little DOM dark inside of an HTML member that you, a developer, confirm to put it in. The digest of a shade DOM replaces a digest of a horde element’s children. You can reinstate a digest of a horde entirely, nonetheless if it has children we can use a special HTML tab called content to insert them.

Grab a duplicate of Chrome Canary and try personification with a following below:

(Tip: Enable ‘Show Shadow DOM’ in a Web Inspector once we have Canary running!)

If we supplement a select attribute to a content tab we can even mention where specific horde calm appears regulating a classes or IDs of your horde element’s children.

This special DOM is encapsulated from a primogenitor DOM scope. Its essence are unblushing by a CSS and JavaScript in a primogenitor range unless we privately set flags otherwise.

Custom elements and HTML templates

Custom elements regulating a new element and template tags let us announce a member like so in a possess HTML file:

Then, we can use a tradition member by including an HTML template in a header and requesting an charge to a horde element:

Whenever a template tab is rendered, a Shadow DOM is combined and extrinsic so that a tradition element’s middle workings are encapsulated. The outcome is that a user will see a following rendered in place of a strange host’s children:

  • Inserted by a template!
  • Home
  • Navigation 1
  • Navigation 2
  • Contact Us

Note that if we check this markup in a prior instance with a Chrome Developer Tools in Chrome Canary, we will not see a shade tree, I’m creation a suppositious instance here for those who aren’t reading this essay in an corner recover browser.

Whenever a template tab is rendered, a Shadow DOM is combined and extrinsic so that a tradition element’s middle workings are encapsulated.

Shadow DOM + Custom Elements == Web Components, a unreal browser API we need to make a idea of encapsulated components in a browser come true. Note that during a time of writing, a operative groups obliged for identical on a doing of this underline are now debating possibly tradition elements will use a charge process (detailed in this JSConf EU video), or possibly develoeprs will emanate wholly tradition tags something like this:

There are several merits and flaws with possibly implementation. For a dirty sum and to stay adult to date on a decision, follow this Bugzilla ticket. we tend to cite a tradition tags syntax and approach, for reasons I’ve minute in a aforementioned Bugzilla bug.

If we wish to go by web member examples like a ones in this territory step-by-step, take a demeanour during this video.


  • Encapsulated components, usually what we want!
  • There’s a polyfill so we can play with them, nonetheless we still need Chrome Canary too
  • Easy to emanate for frontend developers
  • Easy for designers to use declaratively with tags in HTML


  • Not implemented in any fast browser channel. Experiments usually work in Chrome Canary. Rumour is that Firefox will follow shortly after collaborative agreement is met about its implementation
  • Loading mixed components could means beyond if we use lots of components as any one is an HTTP ask (HTML templates can be concatenated together, though, to lessen a issue)

X-Tags: a tradition elements polylib

X-Tags is a member library and registry put together by some folks during Mozilla. It uses a tradition HTML tab proceed over a charge process used as an instance to broach shade DOM and web components.

The syntax to use a tradition tab with this library can be as elementary as:

X-Tags boasts a good registry of components accessible for we to use already. You’ll need to familairise yourself with a really little API during x-tags.org to register your tab and hoop events with it to get going.

This library will feel identical to other frontend UI member frameworks that you’ve worked with before, solely this is not a horizon during all: you’re giveaway to use a components in a registry in any proceed we would like nonetheless any formidable hierarchy of dependencies; there are no additional facilities stealing that we don’t need; there is no general-purpose library grow since X-Tags is smart; it is itself a member since it usually does one thing really well; and it lets we make tradition components.

Eventually a library looks like it will confederate shade DOM and web components as those specs finally indurate and make their proceed into vital browser channels.

Eventual encapsulation? we wish so, since afterwards this competence find a mark absolutely in my developer toolchain.


  • Will eventually use a web member and shade DOM customary implementations when they are finally concluded upon
  • Populated, organized eco-system of micro-modules accessible to use today
  • The doing is really barebones so we can hang to vanilla JavaScript
  • Easy to emanate for frontend developers
  • Easy for designers to use declaratively in HTML
  • Heavy importance on cross-browser compatibility, generally mobile


  • No loyal encapsulation yet. But it seems like a developers are implementing from a W3C specifications already and so we should design shade DOM to answer this problem in future


As web components and improved encapsulation find their proceed into a workflow, we design that we’ll see a welfare for client-side turn a norm. While client-side templating is already a renouned proceed to emanate apps full of features, offloading some-more of a work to a browser could meant that we have reduction formula entrance over a handle in sequence to accomplish a goals.

This office is generally critical deliberation a impact of downloading over dangerous and, sometimes, slower mobile connectors on user experience. Nobody likes a delayed web app.

I’m anticipating that shortly I’ll have a member toolbox during my ordering done with tradition tags. With a reusability and a elementary declarative inlet of tradition elements, designers and UX professionals that are unknown with programming nonetheless do know HTML will be means to fast antecedent some-more worldly use cases by usually regulating a tradition tags that I’ve created.

I don’t design that any general widget will solve each underline ask right out of a box, nonetheless if we hang to a minimalist member truth afterwards we can start with something elementary and supplement usually what we need.

This year, use essay your formula in a proceed that is some-more modular and follow a swell of these new browser facilities as they develop. You’ll appreciate yourself after for being forward of a curve.

Further resources

  • There’s a video of my JSConf EU speak Inspector Web and a Mystery of a Shadow DOM to watch
  • Shadow DOM 101 focuses on a pivotal underline of shade DOM: a ability to apart calm from presentation
  • The Web Components Explainer will give your some-more dirty sum about web components with a slightest succinct denunciation compared with other W3C docs
  • TJ Holowaychuck on what creates a good member that we should review (and subsequently launched a registry of components to be used with CommonJS)
  • Here’s that slip rug from developer Ben Vinegar on seamless iframes again in box we missed it
VN:F [1.9.22_1171]
Rating: 10.0/10 (1 opinion cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)
Writing modular frontend components in 2013, 10.0 out of 10 formed on 1 rating

Leave a Comment

Comments are moderated. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!

3 × nine =