Веб-компоненты — это новый стандарт, часть спецификации HTML. Функциональность позволяет браузеру делать то, что делает браузеры, и в частности писать приложения для браузеров чем-то быстрым, чистым, тестируемым, безопасным и надежным. Основы, поддерживающие веб-компоненты, реализованы производителями браузеров: Google, Mozilla, Microsoft и Apple и другими.
Компоненты — это разделяемые фрагменты функциональности, которые значительно ускоряют разработку надежных веб-приложений, о которых вы можете прочитать подробнее здесь, если вы гик.
Зачем нам нужны веб-компоненты
Зайдите на Домашнюю страницу Amazon и посмотрите.
Я вижу шапку, окно поиска, большое промо для видео Amazon Prime и несколько прокручивающихся горизонтальных разделов (известных в бизнесе как «карусель»), содержащих новые для меня вещи, женскую весеннюю одежду, фильмы, книги, налоги. программное обеспечение и так далее. Чтобы достичь этого, нам нужно написать программное обеспечение, которое в конечном итоге выдаст что-то вроде этого:
<div id="uber-widget-ns_1V1SCR4KS1Q8H4M6QEG0_2054_" class="a-section a-spacing-none shogun-widget uber-widget aui-desktop fresh-shoveler">
<div class="a-section as-title-block">
<span class=as-title-block-left>
<span class="a-color-base">
New For You
</span>
</span>
<span class="as-title-block-right">
<a class="a-link-normal" href="/gp/yourstore/nr/ref=s9_newr_gw_clnk?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=1V1SCR4KS1Q8H4M6QEG0&pf_rd_t=36701&pf_rd_p=1970559082&pf_rd_i=desktop">
See more
</a>
</span>
</div>
What's a <div>? What's a <span> What's an <a>? How about class, href? It's HTML.
Well... in this case they are ways to group and organize what you see on the screen. <div> and <span> are kind of "holders" for stuff. What stuff, what it looks like, how it acts -- all of this is determined by all the bits like class="a-section as-title-block" which a team at Amazon needed to design, develop, test, and make work.
And it gets worse. The real software that makes all of this work is elsewhere and it's way more complicated. There's JavaScript, a programming language that browsers know how to run, and there's CSS which uses those class definitions to define little bits of color, layout and other style.
Oh yeah, there's also the content like pictures and words.
The whole web page has 11 thousand lines of these things; the vast majority of it is JavaScript software.
Um yeah, I did just say eleven thousand lines of HTML all of which was sent to my browser just so I could see the home page.
We get a very nice, interactive, dynamic and customized web page just for me.
It gets worse
But there's stuff I didn't show in the first example which starts like this
<li data-sghover="{"asin":"B007GFGTAW","type":"slideout"}" class="feed-carousel-card"><span class="a-list-item"><a class="a-link-normal a-inline-block" href="/gp/product/B007GFGTAW/ref=s9_newr_gw_d50_g351_i1?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=1V1SCR4KS1Q8H4M6QEG0&pf_rd_t=36701&pf_rd_p=1970559082&pf_rd_i=desktop"><img alt="The One That Got Away" src="http://ecx.images-amazon.com/images/I/51WMWTfUMAL._AC_SY220_.jpg"
This is a little bit of software, some more html, and a tiny bit of data -- the link to the image, and the title of the first item, a book. But none of this does anything until we get to the fun stuff:
<script type="text/javascript">
P.when('A').execute(function(A) {
var $ = A.$;
var Carousel = function ($carousel) {
var self = this;
this.init($carousel);
};
Carousel.prototype = {
init: function ($carousel) {
var self = this;
if (A.$('html').hasClass('a-touch')) {
$carousel.addClass('feed-carousel-touch');
}
self.minItems = 10;
self.$carousel = $carousel;
self.touch = self.$carousel.hasClass('feed-carousel-touch');
self.$shelf = self.$carousel.find('.feed-carousel-shelf');
self.$viewport = self.$carousel.find('.feed-carousel-viewport');
self.$spinner = self.$carousel.find('.spinner');
and this goes on for 300 lines. Don't forget that $ sign!
Web Components don't make this go away, they just make it vastly less crazy and unmanageable.
What Is A Component, Anyway
A component is just a bit of capability that a browser knows how to handle when you tell it to.
Current versions of HTML have components already! There are indeed HTML elements like <button> and <checkbox> and without any special magic they do what you expect. Clicky-ness, the look, and what happens is all built in -- you might tweak it a bit to give it style and behavior you want, but mostly it just works.
Unfortunately, there are only about 15 or 20 of these elements, and the rest are left to the developer. Sadly, the elements available don't do anything like what we expect modern web or mobile software to do. These elements have been largely the same since HTML was created.
So enter web components. Web Components let me, the developer, create my own things that, like checkboxes, handle data, have behavior, and can even display something.
I have just created a web component (in my head), and now could send the following back to the browser, along with a little bit of other stuff, and my Amazon home page might look like
<promo-carousel new-for-you data-product_ids="B007GFGTAW,B007GWQYE,B007GUIWS"></promo-carousel>
<promo-carousel womens-early-spring data-product_ids="B007GFGTAW,B007GWQYE,B007GUIWS"></promo-carousel>
This is better, right? It almost, kind of makes sense to normal humans.
To be sure, it took me a while to make the software that did all of this. (Actually it was fast, because I just imagined it. Someone would have to actually write it.)
But there are some huge differences between what we do now and what we'll do using web components.
Web Components Let You Define Your Own Elements
We have been writing reusable components in software forever. But doing so for the web has required stuff like the above.
Using current web design, what you see, how it works, and the actual content are all tangled up. This makes it very hard to build, very hard to test, very hard to read, and understand.
The same people who are creating beautiful designs have to wade through the other stuff that only programmers really understand. These are components, they are clumps of similar software. It's not reusable. It tends to work differently when on different browsers, different screen sizes and different devices. Slowly.
By letting us break out of </checkbox><checkbox> and make our own things that know how to look, behave and handle data we bring the web much closer to real software. We can separate the parts involving the data, from how it behaves, from how it looks.
It turns out that people good at things like data tend to suck at making things look nice. And people who are great at designing beautiful things who also know how to make things work and work with data are known as unicorns.
Unicorns are mythical creatures that don't actually exist.
So if you're frustrated with the pace and quality of what we develop for the web today, take our your anger on Microsoft who prevented the natural and speedy evolution of the parts that make up the web with their much despised Internet Explorer.
If you're feeling especially venomous or you're just a hater, you can also legitimately blame MS for spam, viruses, and phishing, but that's another post. Fortunately, Microsoft has gone away and now is playing catch-up with Google and Firefox. Maybe Apple will play nice, too (or not?)
What Aren't Web Components?
Web Components don't take away the need to build services on web servers. Rails, Django, and various Java apps can still exist. Indeed, they'll be happier because they can focus on things that web servers and their applications are good at: managing code and data securely. Instead of spewing all that text I pasted in from Amazon at the beginning, they can send just the raw data, plus the code for the needed components.
The front-end ... browsers supporting Web Components can have all the clever logic needed to have a very responsive and engaging user experience that, for once we can build in the same way, using the same disciplines as we do to build server-side software.
When Are Web Components
Making web components work partly involves making browsers able to do things they don't know how to do well.
Actually, for the last month or so Google's Chrome browser has known how to do the things needed by Web Components. It's here, now.
Google's Polymer project has been working with the Chrome team, with the goal of making it possible to use Web Components on "modern" browsers. Currently this means Chrome and Firefox, and maybe with lots of asterisks IE 11 and a few more with Safari (the browser on iOS).
If you can make your users use Chrome, you're good today, so this might be perfect for an internally developed enterprise application. For the real world, it's a while. And a key part is support from IE and Safari.
Because Speed Counts
Doing this coolness within the browser means that that fancy computer you got can do what it's good at: computing stuff. Until web components are baked into the browser software that your computer runs, the alternatives are to fake out the browser with some good ol' JavaScript, but this is a step away from running on your computer -- it's your computer running your browser, and your browser running software written in JavaScript. That's a lot slower.
Mobile Is Why Speed Counts
I haven't yet mentioned an important thing: phones and tablets. If you want to build an app for your iPad or Android phone you have to re-write all that software you wrote for the web in two (count 'em) separate languages. No one writing business software really does this, because it's possible to kind of "wrap" your well-designed web software into an app (using tools like PhoneGap or Cordova) for the phone or tablet so it is a native application that you can sell on the App Store or Google Play.
But it's not. Such apps are warmed over websites -- game developers or others wanting a truly "native" experience or speed write software specially for each device.
Yeah, it sucks. Mostly you can use your underlying software to do all the heavy lifting, but that user interface still needs to be crammed into a different size, and works a little differently.
So you can get away with having a website that works well enough on mobile. Take a look at this site on a phone or tablet. Not bad, eh? This only works because I am using a plugin called wp-touch that is designed to work with WordPress sites like this. I do nothing. But a blog is not an app. You just read. It doesn't have to be fast or know about the phone or GPS. It's just a warmed over website.
Building a real app, is different than building for a computer browser. You can provide the kind of capabilities that your users need and want in the context of their tablet (lying on back on couch) or phone (waiting for airplane or in a meeting). Doing this means writing multiple different apps for different platforms, and most of us don't have that much time on our hands. So we use PhoneGap and some of the techniques that make this website look and operate differently on a phone or tablet.
But you're stuck with the web browser built into the phone or tablet. Android is probably OK, because that browser is Chrome which already has Web Components. But there's a little company called Apple you might have heard of. Until they support Web Components, we're not quite there yet.
Remember that speed problem? While you might be able to do some Web Components stuff with the browser built into the iPhone operating system, it's going to be pokey and probably take a lot of work to make it right. In the end, you probably have to write a couple of versions. And that sucks.
Web Components Have Landed, but the Invasion Has Just Started
We have time to get this right. And like any new technology, it's going to be another year or so, depending on what you want to do, before deploying an app using Web Components is a practical thing.
But when they come, Web Components will dramatically simplify, rationalize, and speed up the development of applications on all devices.