The Web Component module is divided into template elements, Shadow DOM, custom elements and HTML Import
Template elements
1. Template elements
html elements include css, html and javascript, which are reusable. W3C Web Component specification includes elements. For web development, template is still too new, so compared with Handlebars.js For this rather mature library, the Web Component template lacks some functions. Of course, it will be powerful soon.
2. IDL
The < template > element is an HTMLTemplateElement interface. The specific IDL (the language used by W3C to define the specification) is defined as follows
#DOM Interface interface HTMLTemplateElement : HTMLElement { readonly attribute DocumentFragment content; };
- HTMLTemplateElement: This is the template interface, which inherits the HTMLElement class
- Content - this is the only element in the HTML template. It returns the content of the template and is read-only
- DocumentFragment - this is the type returned by content, can be regarded as a lightweight document, and has no parent element
3. Delayed loading of template elements
Template elements are loaded late, as shown in the following example
<div id="message"></div> <template id="aTemplate"> <img id="profileImage" src="http://www.gravatar.com/avatar/c6e6c57a2173fcbf2afdd5fe6786e92f.png"> <script> alert("This is a script."); </script> </template> <script> (function(){ var imageElement = document.getElementById("profileImage"), messageElement = document.getElementById("message"); messageElement.innerHTML = "IMG element "+imageElement; })(); </script>
The running results of Google are as follows
We can see the above document Getelementbyid ("profileImage") has no value, that is, the aTemplate has not been loaded.
4. Activate nodes in the template
Therefore, this proves that the template is loaded late. How to activate the nodes in the template? There are two methods, clone nodes and import nodes
a clone node
<div id="message"></div> <template id="aTemplate"> <img id="profileImage" src="./WechatIMG828.png" width="100" height="100"> <script> alert("This is a script."); </script> </template> <script> (function(){ const messageEl = document.getElementById("message"); const aTemplate = document.querySelector("#aTemplate"), templateContent = aTemplate.content, activeContent = templateContent.cloneNode(true); // object DocumentFragment messageEl.appendChild(activeContent); })(); </script>
b. Import node
<div id="message"></div> <template id="aTemplate"> <img id="profileImage" src="./WechatIMG828.png" width="100" height="100"> <script> alert("This is a script."); </script> </template> <script> (function(){ const messageEl = document.getElementById("message"); const aTemplate = document.querySelector("#aTemplate"), templateContent = aTemplate.content, activeContent = document.importNode(templateContent, true); messageEl.appendChild(activeContent); })(); </script>
2, HTML Import
1.HTML Import
HTML Import is also an important part of the web c specification. External HTML documents can be embedded into the current document through HTML Import, similar to iframe.
2. IDL
partial interface LinkImport { readonly attribute Document? import; }; HTMLLinkElement implements LinkImport;
Note: HTML Import has been deprecated.
3, Shadow DOM
1. Advantages
- Style override
- Script replacement
- Duplicate ID
2. DOM type
Shadow DOM allows us to insert a DOM subtree into the document being rendered. As we all know, DOM is a tree structure, and the child nodes of each DOM tree can have their own shadow DOM tree. In this way, the DOM will be like a "recursive" tree. We can divide the DOM tree into three types
- Document tree: the most common DOM tree. The following node is the document itself
- Shadow tree: the DOM subtree inside the document, which is also composed of HTML elements, but the following node is called shadow root
- Composite tree: it has both traditional DOM tree and Shadow DOM tree, which can also be used by browsers to render pages
A DOM element with at least one Shadow DOM subtree is called a host element, also known as Shadow host
3. IDL
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; };
4. Example
<div id="aShadowHost"></div> <script> var aShadowHost = document.getElementById("aShadowHost"), aShadowRoot = aShadowHost.createShadowRoot(); aShadowRoot.innerHTML = "<h1>Hi, this is example of shadowDOM.</h1>"; </script>
4, Custom element
The Web Component specification also stipulates that if a new element is created in the DOM, the custom element can have its own attributes and methods.
1. User defined element life cycle
#Life cycle callback methods of an element createdCallback : An instance of the element is created. attachedCallback : An instance was inserted into the document. detachedCallback : an instance was removed from the document. attributeChangedCallback(attrName, oldVal, newVal): an attribute was added, removed, or updated. Object.create(<target prototype>[, propertiesObject]); Object.defineProperty(<target object>, <property name>, <configuration>); Object.defineProperties(<target object>, <properties>);
2. Example
<head lang="en"> <meta charset="UTF-8"> <title>Web Component: custom element example</title> <script type="text/javascript" src="./webcomponentsjs/webcomponents.min.js"></script> <script> var objectPrototype = Object.create(HTMLElement.prototype); Object.defineProperty(objectPrototype, 'title', { writable : true }); objectPrototype.createdCallback=function(){ this.innerText=this.attributes.title.value; }; var myNameElement = document.registerElement("my-name",{ prototype:objectPrototype }); </script> </head> <body> <my-name title="Welcome to custom element 1"></my-name> <br> <my-name title="Welcome to custom element 2"></my-name> </body>
5, Polyfill
Although most browsers do not support web component yet, there is a compatible library called webcomponentsjs that allows web component to run on browsers that do not support it. As long as you introduce this library into the project, you can use web components like the above example.
At present, the browser has not fully implemented the web component specification, but there are many polyfill of web component Well,
- Developed by Google, polymer - allows web developers to write CSS, HTML, and js to build powerful, content rich, and highly available web components.
- Mozilla Brick maintained by Mozilla is another web component library, which provides a large number of UI components that can be reused in web applications
- Facebook also has its own web component library, ReactJS.
- Bosonic's core code uses some polymerJS
1. Polymer
polymer It is a framework developed by google to support the development of web component. Generally speaking, it is based on the web component specification proposed by w3c. Before the specification is implemented by all browsers, polymer also added some syntax sugar to the web component standard. The purpose of polymer is to try to implement the web component specification completely by the browser.
The Polymer library is built on multiple technical layers, each of which has a specific role
- core element Used to create UI and non UI elements in web pages, such as icons, layouts, toolbars, AJAX, signals, and storage elements
- Paper element -Built on the core elements of Polymer, the UI of these elements is richer than that of core
- polyfill of Polymer is also webcomponentsjs
- Git
2. Lit
Lit — Google's web components library, the core of which is a component base class designed to reduce boilerplate while providing reactive state, scoped styles, and a declarative template system.
LitElement A simple base class for using to create fast, lightweight Web components. His polyfill is webcomponentsjs
Note: This is the current stable version of the Polymer library. At Google I/O 2018 we announced a new Web Component base class. LitElement as a successor to the PolymerElement base class in this library.
If you're starting a new project, we recommend that you consider using LitElement instead.
3. Bosonic
Bosonic It is a class library based on W3C specification and can be used to develop web component s. Bosonic can support less modern browsers, such as ie9. Bosonic is built on PolymerJS and its own polyfill.
Bosonic is like a transformation compiler. The conversion compiler is a simple compiler that can convert the input source code into another programming language.
The Bosonic transformation compiler reads the elements defined by HTML and generates the corresponding js and css files.
4 Mozilla Brick
Mozilla provides a javascript library called x-Tag to assist the development of web components. This library is based on the web component polyfill developed by the Polymer team, and the Mozilla Bricks framework is also based on the x-Tag library
Mozilla Brick1.0 is based on X-Tag
Mozilla Brick The library provides a series of elements based on the web component specification. The purpose of the brick framework is strong options, tightly scoped, which means that the brick framework will not pay attention to code structure, data binding, and other problems. It provides a web interface that can be easily integrated with other libraries. The brick element is developed based on the custom element API. This custom element API includes shadow DOM, HTML import, template element and custom element. Brick provides a standard interface that can easily intervene in other application frameworks.
Brick component is developed from pure JS.
v1.0
- Platform: This indicates a feature that is not supported by the natively supported web c specification and polyfill file
- X-Tag: the X-Tag library required to create the element
- Brick web component: it represents the UI control collection of built-in elements used by developers in web applications
v2.0
- Platform: This indicates a feature that is not supported by the natively supported web c specification and polyfill file. The polyfill file here is platform js,
Used by polymerJS. In the current version of polymerJS, platform The. JS file was renamed webcomponents.js js - Brick web component: it represents a series of built-in UI elements that developers can use in web applications.
5. ReactJS
Flux architecture
Flux The architecture is as follows
- View: this layer is used to represent UI components. It will be rendered on the browser side for users to use
- Store:
This layer maintains data and business logic, which is similar to the model layer of traditional MVC mode. store represents a series of data objects, while model represents a single data object - Dispatcher: this layer is a transit station through which all action s pass, including all callback functions registered in the store
The application development mode in Flux architecture is as follows:
- a. Generally speaking, actions are generated by the interaction between users and views. These actions are asynchronous in nature
- b. These actions are transferred to the dispatcher for processing, and then the dispatcher will call the callback function registered in the store
- c. The execution of the callback function may change the state of the data, and then the store starts the change event and passes in the updated data.
The View will listen to the change event, and the event listener will accept the new data passed in from the store. Then, the View
The setState method is called to re render itself and its child elements. - d. The data flow is one-way. The Flux architecture does not allow two-way binding, because two-way binding will cause cascading updates
Key features of Flux
- Synchronization: the callback function registered by each Action is executed synchronously, and the Action is triggered asynchronously
- Inversion of control: the control of data flow will be transferred to the appropriate store object and target callback
- Semantic Action: when triggering an Action, you need to include some semantic information, which can help the store object to execute appropriate methods
There is no cascading Action: cascading Action is not allowed in FLux because it will cause multiple updates.
What is JSX
ReactJS also has JSX, which represents Javascript XML, which follows XML type element declarations for developing web c benefits
Easy to get started: developers are already familiar with XML, and JSX provides the same way to declare elements
2 semantics: JSX is easier to understand because it is a declarative programming method
3 separation of concerns: JSX provides a clear way to encapsulate all logic and tags in one declaration
JSXTransformer.js file realizes the conversion of JSX code into acoustic JS on the browser side. This browser side compilation is not recommended
1. Additional computing cost: compiling JSX in real time on the client will reduce the rendering speed
2. File size: jsxtransformer JS is very large, which will increase the loading time of the client.
Therefore, it is best to compile offline, such as using react tool
ReactJS features, JSX, virtual DOM, custom component development, etc