Learning Web Component Development - Sample Chapter
Learning Web Component Development - Sample Chapter
Learning Web Component Development - Sample Chapter
$ 39.99 US
26.99 UK
P U B L I S H I N G
ee
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Sa
m
Instant GSON
Preface
Welcome to Learning Web Component Development. If you want to learn and
understand the W3C web component specification and develop a custom web
component using Polymer, Bosonic, Mozilla Brick, and ReactJS, then this is the book
for you. It offers a systematic approach to build a responsive web application. All
the key features of web component specification that can help in building a web
component are explained in this book, and are accompanied by the detailed code
you will need.
Preface
Appendix, Web Component References, lists all of the online sites and forums on web
component for further study.
A web component has a template that can be used to put the entire markup
separately, making it more maintainable.
As web components are developed using HTML, CSS, and JavaScript, it can
run on different browsers. This makes it platform independent.
Shared resource: A web component has its own scoped resources. There may
be cases where some of the resources between the components are common.
Polyfill size: The polyfill are a workaround for a feature that is not currently
implemented by the browsers. These polyfill files have a large memory
foot print.
SEO: As the HTML markup present inside the template is inert, it creates
problems in the search engine for the indexing of web pages.
[2]
Chapter 1
These four pieces of technology power a web component that can be reusable across
the application. In the coming section, we will explore these features in detail and
understand how they help us in web component development.
Template element
The HTML <template> element contains the HTML markup, style, and script,
which can be used multiple times. The templating process is nothing new to a web
developer. Handlebars, Mustache, and Dust are the templating libraries that are
already present and heavily used for web application development. To streamline
this process of template use, W3C web component specification has included the
<template> element.
This template element is very new to web development, so it lacks features
compared to the templating libraries such as Handlebars.js that are present in
the market. In the near future, it will be equipped with new features, but, for now,
let's explore the present template specification.
The preceding code is written in IDL language. This IDL language is used by the
W3C for writing specification. Browsers that support HTML Import must implement
the aforementioned IDL. The details of the preceding code are listed here:
content: This is the only attribute of the HTML template element. It returns
have a parent.
Chapter 1
} else {
message.innerHTML = "Template element is not supported by
the browser.";
}
</script>
</body>
</html>
The preceding screenshot shows that the browser used for development is
supporting the HTML template element.
There is also a great online tool called Can I Use for checking
support for the template element in the current browser. To check
out the template support in the browser, use the following link:
http://caniuse.com/#feat=template
[5]
The following screenshot shows the current status of the support for the template
element in the browsers using the Can I Use online tool.
Inert template
The HTML content inside the template element is inert in nature until it is activated.
The inertness of template content contributes to increasing the performance of the web
application. The following code demonstrates the inertness of the template content:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>
Web Component: A inert template content example.
</title>
</head>
<body>
<div id="message"></div>
<template id="aTemplate">
<img id="profileImage"
src="http://www.gravatar.com/avatar/
c6e6c57a2173fcbf2afdd5fe6786e92f.
png">
<script>
[6]
Chapter 1
alert("This is a script.");
</script>
</template>
<script>
(function(){
var imageElement =
document.getElementById("profileImage"),
messageElement = document.getElementById("message");
messageElement.innerHTML = "IMG element "+imageElement;
})();
</script>
</body>
</html>
In the preceding code, a template contains an image element with the src attribute,
pointing to a Gravatar profile image, and an inline JavaScript alert method. On
page load, the document.getElementById method is looking for an HTML element
with the #profileImage ID. The output of the preceding code is shown in the
following screenshot:
[7]
The preceding screenshot shows that the script is not able to find the HTML element
with the profileImage ID and renders null in the browser. From the preceding
screenshot it is evident that the content of the template is inert in nature.
Activating a template
By default, the content of the <template> element is inert and are not part of the
DOM. The two different ways that can be used to activate the nodes are as follows:
Cloning a node
Importing a node
Cloning a node
The cloneNode method can be used to duplicate a node. The syntax for the
cloneNode method is listed as follows:
<Node> <target node>.cloneNode(<Boolean parameter>)
The input parameter for this method is of the Boolean type and represents
a type of cloning. There are 2 different types of cloning, listed as follows:
Deep cloning: In deep cloning, the children of the targeted node also
get copied. To implement deep cloning, the Boolean input parameter
to cloneNode method needs to be true.
The following code shows the use of the cloneNode method to copy the content of a
template, having the h1 element with some text:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>
Web Component: Activating template using cloneNode method
</title>
</head>
[8]
Chapter 1
<body>
<div id="container"></div>
<template id="aTemplate">
<h1>Template is activated using cloneNode method.</h1>
</template>
<script>
var aTemplate = document.querySelector("#aTemplate"),
container = document.getElementById("container"),
templateContent = aTemplate.content,
activeContent = templateContent.cloneNode(true);
container.appendChild(activeContent);
</script>
</body>
</html>
In the preceding code, the template element has the aTemplate ID and is referenced
using the querySelector method. The HTML markup content inside the template is
then retrieved using a content property and saved in a templateContent variable.
The cloneNode method is then used for deep cloning to get the activated node that
is later appended to a div element. The following screenshot shows the output of the
preceding code:
[9]
Importing a node
The importNode method is another way of activating the template content.
The syntax for the aforementioned method is listed in the following code:
<Node> document.importNode(<target node>,<Boolean parameter>)
This method takes two input parameters. The first parameter is the target
node that needs to be copied. The second parameter is a Boolean flag and
represents the way the target node is cloned. If the Boolean flag is false,
the importNode method makes a shallow copy, and for a true value, it
makes a deep copy.
The following code shows the use of the importNode method to copy the content of a
template containing an h1 element with some text:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>
Web Component: Activating template using importNode method
</title>
</head>
<body>
<div id="container"></div>
<template id="aTemplate">
<h1>Template is activated using importNode method.</h1>
</template>
<script>
var aTemplate = document.querySelector("#aTemplate"),
container = document.getElementById("container"),
templateContent = aTemplate.content,
activeContent = document.importNode(templateContent,
true);
[ 10 ]
Chapter 1
container.appendChild(activeContent);
</script>
</body>
</html>
In the preceding code, the template element has the aTemplate ID and is referenced
using the querySelector method. The HTML markup content inside the template
is then retrieved using the content property and saved in the templateContent
variable. The importNode method is then used for deep cloning to get the activated
node that is later appended to a div element. The following screenshot shows the
output of the preceding code:
[ 11 ]
HTML Import
The HTML Import is another important piece of technology of the W3C web
component specification. It provides a way to include another HTML document
present in a file with the current document. HTML Imports provide an alternate
solution to the Iframe element, and are also great for resource bundling. The syntax
of the HTML Imports is listed as follows:
<link rel="import" href="fileName.html">
The HTML file can be imported using the <link> tag and the rel attribute
with import as the value.
The href string points to the external HTML file that needs to be included in
the current document.
The HTML import element is implemented by the HTMLElementLink class. The IDL
definition of HTML Import is listed in the following code:
partial interface LinkImport {
readonly attribute Document? import;
};
HTMLLinkElement implements LinkImport;
The preceding code shows IDL for the HTML Import where the parent interface is
LinkImport which has the readonly attribute import. The HTMLLinkElement class
implements the LinkImport parent interface. The browser that supports HTML
Import must implement the preceding IDL.
Chapter 1
<body>
<h1 id="message"></h1>
<script>
var isImportSupported = function () {
var link = document.createElement("link");
return 'import' in link;
};
var isSupported = isImportSupported(),
message = document.getElementById("message");
if (isSupported) {
message.innerHTML = "Import is supported by the browser.";
} else {
message.innerHTML = "Import is not supported by the
browser.";
}
</script>
</body>
</html>
The preceding code has a isImportSupported function, which returns the Boolean
value for HTML import support in the current browser. The function creates a <link>
element and then checks the existence of an import attribute using the in operator.
The following screenshot shows the output of the preceding code:
[ 13 ]
The preceding screenshot shows that the import is supported by the current browser
as the isImportSupported method returns true.
The Can I Use tool can also be utilized for checking support for the
HTML Import in the current browser. To check out the template
support in the browser, use the following link:
http://caniuse.com/#feat=imports
The following screenshot shows the current status of support for the HTML Import
in browsers using the Can I Use online tool:
[ 14 ]
Chapter 1
The following code shows the HTML document where the message.html file is
loaded and referenced by the import property:
<!DOCTYPE html>
<html>
<head lang="en">
<link rel="import" href="message.html">
</head>
<body>
<script>
(function(){
var externalDocument =
document.querySelector('link[rel="import"]').import;
headerElement = externalDocument.querySelector('h1')
document.body.appendChild(headerElement.cloneNode(true));
})();
</script>
</body>
</html>
In the header section, the <link> element is importing the HTML document
present inside the message.html file.
The header h1 element inside the external document is then located using
a querySelector method and saved to the headerElement variable.
The header element is then deep copied using the cloneNode method
and appended to the body element of the current document.
[ 15 ]
load: This event is fired when the external HTML file is imported
Chapter 1
The following code shows the use of these two event types while importing the
message.html file to the current page:
<!DOCTYPE html>
<html>
<head lang="en">
<script async>
function handleSuccess(e) {
//import load Successful
var targetLink = e.target,
externalDocument = targetLink.import;
headerElement = externalDocument.querySelector('h1'),
clonedHeaderElement = headerElement.cloneNode(true);
document.body.appendChild(clonedHeaderElement);
}
function handleError(e) {
//Error in load
alert("error in import");
}
</script>
<link rel="import" href="message.html"
onload="handleSuccess(event)"
onerror="handleError(event)">
</head>
<body>
</body>
</html>
[ 17 ]
Shadow DOM
Before the web component specification, there were many issues of building
web applications using HTML, CSS, and JavaScript. Some of the issues are listed
as follows:
Style override: The document stylesheet may change the style of the web
component.
Script alteration: The document JavaScript may alter some part of the web
component.
From the aforementioned issue list, there is clearly a problem with scoping. Shadow
DOM is another important piece of web component specification that solves the
scoping problem by the encapsulation mechanism. Shadow DOM provides a way
of packaging the HTML, CSS, and JavaScript for a web component.
[ 18 ]
Chapter 1
Most of the HTML5 elements, such as the progress bar, are implemented as Shadow
DOM by the Chrome browser. We can inspect this Shadow DOM through the
Chrome developer console. By default, the Chrome developer console will not show
Shadow DOM. We need to enable the Show user agent shadow DOM checkbox
present inside the settings of the developer console. The following screenshot shows
the Chrome developer console setting to enable Shadow DOM inspection:
After enabling the Shadow DOM inspection setting, we can inspect the <progress>
HTML5 element. The following screenshot shows the Chrome developer inspection
of the progress bar element containing Shadow DOM node:
[ 19 ]
In the preceding screenshot, we can see a new element #shadow-root. This node
is the Shadow DOM of the progress bar element. As the progress bar is built in the
browser element; we can see the user-agent text in parenthesis.
[ 20 ]
Chapter 1
The preceding screenshot shows that the Shadow DOM is supported by the current
browser, as the isShadowDOMSupport method returns true. We can also check
the support of the Shadow DOM using the Can I Use online tool. The following
screenshot shows the status of Shadow DOM support in a different browser:
[ 21 ]
Shadow tree
Shadow DOM brings the ability to include a subtree of DOM elements inside a
document on the rendering time. The nodes inside DOM are organized as a tree
structure. A node inside the DOM tree can have its own Shadow DOM tree. This
makes the DOM a tree of trees. We can classify the DOM tree into three different types:
Document tree: This represents the normal DOM tree whose root node
is a document.
Shadow tree: This represents the internal DOM subtree formed using HTML
elements present inside shadow host. The root node of this tree is called
shadow root.
The DOM element that has one or more than one Shadow DOM subtrees is called as
host element or shadow host. The following diagram shows a sample DOM tree:
In the preceding diagram, we find out that the node present inside the DOM element
represents another subtree, which makes the DOM a tree of trees. A browser which
supports Shadow DOM implementation should follow the IDL definition for
declaring the shadow root element. The IDL of a shadow root element is listed
in the following code:
[ 22 ]
Chapter 1
interface ShadowRoot : DocumentFragment {
HTMLElement getElementById(DOMString elementId);
NodeList getElementsByClassName(DOMString className);
NodeList getElementsByTagName(DOMString tagName);
NodeList getElementsByTagNameNS(DOMString? namespace,
DOMString localName);
Selection? getSelection();
Element? elementFromPoint(double x, double y);
readonly attribute Element? activeElement;
readonly attribute Element host;
readonly attribute ShadowRoot? olderShadowRoot;
attribute DOMString innerHTML;
readonly attribute StyleSheetList styleSheets;
};
getElementById: This method finds the element present inside the Shadow
DOM tree with the given ID
Shadow DOM tree with the given namespace and tag name
getSelection: This method returns the selection object for currently selected
element inside the Shadow DOM tree
elementFromPoint: This method returns the element with the given x and y
coordinates
innerHTML: This property returns the HTML content of the shadow root
[ 23 ]
Now, let's check out an example which demonstrates the use of these properties
and the methods of a shadow root. The example code is listed as follows:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Shadow Root: Method & Properties example</title>
</head>
<body>
<div id="aShadowHost"></div>
<template id="selectorTemplate">
<style>
:host input{
background: lightyellow;
}
:host .labelClass{
color: blue;
}
</style>
<form>
<label for="nameElement"
class="labelClass">Name</label>
<input type="text" id="nameElement"
placeholder="Enter your name"
value="Sandeep" autofocus>
</form>
</template>
<script>
(function(){
var aShadowHost = document.getElementById("aShadowHost"),
shadowRoot1 = aShadowHost.createShadowRoot(),
shadowRoot2 = aShadowHost.createShadowRoot(),
templateContent =
document.querySelector('#selectorTemplate').content,
templateNodes = document.importNode(templateContent,
true);
shadowRoot1.innerText ="inside shadowRoot1";
shadowRoot2.appendChild(templateNodes);
shadowRoot2.getElementById("nameElement").select();
//Shadow Root Methods
console.log("getElementById:
",shadowRoot2.getElementById("nameElement"));
console.log("getElementsByClassName:
",shadowRoot2.getElementsByClassName("labelClass"));
console.log("getElementsByTagName:
",shadowRoot2.getElementsByTagName("label"));
console.log("getElementsByTagNameNS:
",shadowRoot2.getElementsByTagNameNS("*","label"));
console.log("getSelection() Method:
[ 24 ]
Chapter 1
",shadowRoot2.getSelection());
console.log("elementFromPoint:
",shadowRoot2.elementFromPoint(8,9));
//Shadow Root Properties
console.log("activeElement: ",shadowRoot2.activeElement);
console.log("host: ",shadowRoot2.host);
console.log("olderShadowRoot:
",shadowRoot2.olderShadowRoot);
console.log("styleSheets: ",shadowRoot2.styleSheets);
console.log("innerHTML: ",shadowRoot2.innerHTML);
})();
</script>
</body>
</html>
In the preceding code, the two Shadow DOM subtrees shadowRoot1 and shadowRoot2
are present for the host element. The shadowRoot1 subtree is created first and
shadowRoot2 is created later. Hence, the shadowRoot1 subtree is an older shadow
root. The shadowRoot2 subtree contains the HTML markup from a template with the
selectorTemplate ID. The shadowRoot2 subtree has a <form> element containing
a <label> and <input> element. It also contains some CSS styles inside the <style>
element. The output of the preceding code is presented in the following screenshot:
[ 25 ]
The following screenshot shows the console log messages, which demonstrate the
use of the preceding methods for the shadow tree:
The following screenshot shows the console log messages that demonstrate the use
of the preceding properties for the shadow tree:
[ 26 ]
Chapter 1
Custom element
Web component specifications come with the power to create a new element for
DOM. A custom element can have its own properties and methods. The reasons for
creating a custom element are less code from the developer's point of view, creating
a more semantic tag library, reducing the number of div tags, and so on. Once a web
component is developed, it can be used by any application.
[ 27 ]
We can also use the Can I Use online tool to check the support for custom elements.
The following screenshot shows the current status of the browser for custom element
support:
[ 28 ]
Chapter 1
Extending an element
The Object.create method takes two parameters. The first parameter is the target
prototype of the newly created object. The second parameter contains the properties
of the newly created object. The second parameter is optional. The following code
defines a new object:
var objectPrototype = Object.create(HTMLElement.prototype);
In the preceding code, a new object is created that has the HTMLElement.prototype
parameter and is saved in the objectPrototype variable.
To find out more about the Object.create method, use the
following link:
https://developer.mozilla.org/en-US/docs/Web/
JavaScript/Reference/Global_Objects/Object/create
[ 29 ]
targetObject: This represents the target object for which the property needs
to be defined.
writable: This takes a Boolean value. For a true value, the associated
set: This takes a function. It sets the input value to the property.
The following code shows an example of defining a single property named title for
newObject that is writable:
var newObject = Object.create(HTMLElement.prototype);
Object.defineProperty(newObject, 'title', {
writable : true
});
The following code shows an example of defining multiple properties like title
and country for the newObject variable. The title property is writable, and the
country property is not writable and has a fixed value India:
var newObject = Object.create(HTMLElement.prototype);
Object.defineProperties(newObject, {
title:{
writable: true
[ 30 ]
Chapter 1
},
country:{
writable: false,
value: "India"
}
});
The following code shows an example where an object is created using the Object.
create method, and a callback method is attached for the created state:
[ 31 ]
tag-name: This represents the name of the custom element. The name must
be separated with a hyphen.
settings: This takes the configuration option for the custom element.
Extending an element
An element can inherit a native or another custom element. The extend property is
used to inherit another element. The following code shows an example of extending
an <i> element:
var objectPrototype = Object.create(HTMLElement.prototype),
italicElement = document.registerElement("italic-message",{
prototype: objectPrototype,
extends:'i'
});
The is operator is used to define the type of an HTML element. The following code
shows if an element is of the italic type:
<welcome-message is="i">
Hello world
</welcome-message>
[ 32 ]
Chapter 1
[ 33 ]
Node distribution
The composed tree takes part in rendering the DOM inside the browser. The Shadow
DOM subtree of the nodes gets arranged for display. The arrangements of the nodes
are done by a distribution mechanism with the help of specific insertion points.
These insertion points are of two types:
Chapter 1
The following code gives an example of the use of the <content> element with the
select attribute:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Web Component: content insertion point with select
attribute example</title>
<template id="selectorTemplate">
<style>
:host b{
margin: 0px 10px;
}
:host ::content b.fruit{
color:green;
}
:host ::content b.flower{
color:orange;
}
</style>
<h1>
Fruits <content select="b.fruit"></content>.
</h1>
<h1>
Flowers <content select="b.flower"></content>.
</h1>
</template>
<script>
var objectPrototype =
Object.create(HTMLElement.prototype);
objectPrototype.createdCallback=function(){
var shadow = this.createShadowRoot(),
templateContent =
document.querySelector('#selectorTemplate').content,
templateNodes =
document.importNode(templateContent, true);
shadow.appendChild(templateNodes);
};
var myNameElement = document.registerElement("selectorcomponent",{
prototype: objectPrototype
});
</script>
</head>
<body>
<selector-component>
<b class="fruit">Apple </b>
<b class="flower">Rose </b>
<b class="fruit">Orange </b>
[ 35 ]
The HTML template of the custom element has two <content> elements.
One content element filters out all the flowers using the select attribute
with the b.flower value, and the other <content> element filters out all the
fruits using the select attribute with the b.fruit value.
The following screenshot shows the output of the preceding code of filtering fruit
and flower in a separate group:
[ 36 ]
Chapter 1
[ 37 ]
During rendering of the page, the shadow insertion point will take the older
shadow root content and insert it in the shadow insertion point.
The following screenshot shows the output of the preceding code, where the older
shadow root elements are reprojected and rendered inside the <fieldset> element,
which belongs to the younger shadow root, that is, shadowRoot1.
[ 38 ]
Chapter 1
Host pseudo selector: The custom element itself can be referred using the
:host pseudo selector to apply the style attribute. An example of the host
selector is listed in the following code:
:host{
text-transform: uppercase;
}
Shadow pseudo selector: The Shadow DOM subtree of the custom element
can be referred using the ::shadow pseudo selector to apply the style
attributes. An example of shadow selector is listed here:
:host ::shadow h1{
color: orange;
}
Content pseudo selector: The content of the older insertion point element
can be referred using the ::content pseudo selector to apply the style
attributes. An example of content selector is listed in the following code:
:host ::content b{
color: blue;
}
[ 39 ]
Chapter 1
shadow.appendChild(templateNodes);
};
window.setTimeout(function(){
document.registerElement("header-element",{
prototype:objectPrototype
});
}, 3000);
})();
</script>
</head>
<body>
<header-element>
<b>Web Component</b>
</header-element>
</body>
</html>
The host DOM tree is referred using the :host pseudo selector, which has
a style attribute in order to transform the text into capital letters.
The Shadow DOM tree is referred using the ::shadow pseudo selector,
which has a style attribute to change the text color to orange.
The template also has the <content> element, which selects the original
children of <header-element> and puts it into this location. In our example,
the children are wrapped around the <b> tag. We referred this <b> element
using the content selector to apply the style attribute so as to make the text
color blue and the text type italic.
[ 41 ]
The following screenshot shows the output of the preceding code with the
:unresolved pseudo selector style in effect for the first 3 seconds. We can
see the message in red.
Once the element is registered to the DOM, the lifecycle method gets executed and
<header-element> gets upgraded with its Shadow DOM. The following screenshot
shows the final output of the preceding code:
[ 42 ]
Chapter 1
Clock template
Clock template
The digital clock template contains the HTML markup and the CSS styles for rendering
in the browser on activation. The HTML template code and the CSS styles for the clock
component are listed in the following code:
<template id="clockTemplate">
<style>
:host::shadow .clock {
display: inline-flex;
justify-content: space-around;
background: white;
font-size: 8rem;
box-shadow: 2px 2px 4px -1px grey;
border: 1px solid green;
font-family: Helvetica, sans-serif;
width: 100%;
}
:host::shadow .clock .hour,
:host::shadow .clock .minute,
:host::shadow .clock .second {
color: orange;
padding: 1.5rem;
text-shadow: 0px 2px black;
}
</style>
<div class="clock">
<div class="hour">HH</div>
<div class="minute">MM</div>
<div class="second">SS</div>
</div>
</template>
[ 43 ]
The content of the clock element is present inside the <template> element.
The ID of the template element is clockTemplate.
All the CSS style classes are wrapped around the <style> element. The host
clock element is targeted using the :host pseudo selector, and its shadow
tree children are targeted using the ::shadow pseudo attribute and the styles
are applied.
The HTML markup for the clock element is wrapped around the div element
.The parent div element has the .clock class. The parent div element has the
three children div element representing hours, minutes, and seconds.
Chapter 1
secondElement.innerText = date.getSeconds();
}, 1000);
};
var digitalClockElement =
document.registerElement("digital-clock", {
prototype: objectPrototype
});
})();
</script>
The script for registering the clock element is embedded inside a self-calling
function, which saves the reference to the current owner document to
selfDocument variable using document.currentScript.ownerDocument.
A new shadowRoot object is created for the host element using the
createShadowRoot method. Reference to this shadowRoot is then
saved to the shadow variable.
The template content of the clock element is then retrieved using the
selfDocument reference variable.
The inert content of the clock template is then activated using the
document.importNode method.
The clock element is then registered with the DOM using the document.
registerElement method. After registering, the clock component is now
ready for use.
[ 45 ]
In the preceding code, the clock component is imported using the link element
with the rel attribute, which has the import value. The digital clock component
can be implemented using the <digital-clock></digital-clock> custom
element. The output of the preceding code is shown in the following screenshot:
The preceding screenshot shows the digital clock component. The numbers in the
screenshot are showing hours (HH), minutes (MM), and seconds (SS). The following
screenshot shows the developer console of the clock component:
[ 46 ]
Chapter 1
The clock element is imported to the current page and has its own
#document root
The digital clock element has its Shadow DOM tree, which is rendered
as a clock
X-Tag
The X-Tag is a small JavaScript library for web component development by Mozilla.
This library is built on the web component polyfill from Polymer team. The Mozilla
Bricks framework is built on top of the X-Tag library. We can download the X-Tag
library using http://www.x-tags.org/download.
inserted: This event is fired by the element when it is inserted into the DOM
for first time.
[ 47 ]
the DOM.
The lifecycle of the element can be defined inside the lifecycle attribute.
The following code shows the syntax of the lifecycle attribute:
lifecycle:{
created: function(){
// code for created state
},
inserted: function(){
// code for inserted state
},
removed: function(){
// code for removed state
},
attributeChanged: function(){
// code for attributeChanged state
}
}
Chapter 1
},
attributeChanged: function() {
// code for attributeChanged state
}
},
accessors: {
<property name> : {
attribute: {
//type and value of the property
}
}
},
methods: {
<method name> : function() {
//Code for the method
}
},
events: {
'<event type>:delegate(<element>)': function(e) {
//Code for event handler
}
}
});
lifecycle: This property can have code for all states during the lifecycle of
methods: This property can have all the methods that need to be exposed as a
events: This property can have all the element's event binding listeners that
need to be fired based on the user action of the custom element.
accessors: This property can have all the attributes that need the getter and
the element. Therefore, we can define its logic for the custom elements by
implementing the created, inserted, removed, and attributeChanged state.
public API that is to be consumed externally.
setters methods.
Now, it is time to create a custom component using this X-Tag library. The code for
creating an X-Tag base custom element is as follows:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
[ 49 ]
Chapter 1
xtag.register method.
This custom element takes the innerHTML content and wraps it with a <i>
element, which gives it an italic style font.
This custom element has a textColor property name, where a color string
can be given. The value of the textColor property is then applied to the
style property of the <i> element.
An event listener is created using the events property. In the preceding code
a click event type listener is attached to the <i> element. When the <i>
element is clicked on, it shows a message in the console.
The output of the preceding code looks like the following screenshot. It has the
Click Me text and a Make Red button rendered in the browser:
[ 51 ]
When user clicks on the Make Red button, the Click Me text will change to red in
color. The following screenshot shows the Click Me text changed to red:
If the user clicks on the Click Me text, then the event handler attached with it gets
executed and prints the message. The following screenshot shows the console log
message when the user clicks on the X-Tag element:
[ 52 ]
Chapter 1
Polymer
Polymer is the web component library from Google Inc. This library allows a web
developer to compose CSS, HTML, and JavaScript to build rich, powerful, and
reusable web component. In Chapter 2, Introducing Polymer and Chapter 3, Developing
Web Components Using Polymer, we will learn more about this library.
To find out more about Polymer library use the following link:
https://www.polymer-project.org
Mozilla Brick
Mozilla Brick is another web component library from Mozilla. It has a collection of
reusable UI components to be used in web application. The current version of this
library is 2.0. In Chapter 5, Developing Web Components Using Mozilla Brick, we will
learn more about this library.
To find out more about Mozilla Brick library use the following link:
http://brick.readme.io/v2.0
ReactJS
The ReactJS is a library for web component development from Facebook. This library
takes a different approach to build the web application. In Chapter 6, Building Web
Components with ReactJS, we will learn more about the ReactJS library.
To find out more about ReactJS library, use the following link:
http://facebook.github.io/react
Bosonic
Bosonic is another library for web component development. It uses some of the
PolymerJS polyfill in the core. In Chapter 4, Exploring Bosonic Tools for Web Component
Development, we will explore more details about Bosonic.
To find out more about the Bosonic library, use the following link:
http://bosonic.github.io/index.html
[ 53 ]
Summary
In this chapter, we learned about the web component specification. We also
explored the building blocks of web components such as Shadow DOM, custom
element, HTML Imports, and templates. In the next chapter, we will learn about
the PolymerJS library in detail.
[ 54 ]
www.PacktPub.com
Stay Connected: