SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
2.
Custom Elements
• How to build a custom element
• Naming rules
– 至少含有一个 ’-’
– 正确:x-component x-web-component
– 错误:web_component xelement XElement
var XComponent = document.registerElement('x-component');
<x-component></x-component>
3.
Custom Elements
• Imperative usage
var XComponent = document.registerElement('x-component');
var dom = new XComponent();
document.body.appendChild(dom);
document.registerElement('x-component');
var dom = document.createElement('x-component');
document.body.appendChild(dom);
4.
Custom Elements
• Adding features to a custom element
var proto = Object.create(HTMLElement.prototype);
proto.name = 'Custom Element';
proto.alert = function() {
alert('This is ' + this.name);
};
document.registerElement('x-component', {
prototype: proto
});
5.
Custom Elements
• Type Extension Custom Element
– 自定义元素可以是从扩展原生HTML元素而来
– 定义类型扩展
• 创建基本原型对象,使用被扩展元素的原型,而不是使用HTMLElement
• 在document.registerElement()的第二个参数中添加 extends 键,值为被扩展元素的标签名
<div is="x-component"></div>
var XComponent = document.registerElement('x-component', {
extends: 'input',
prototype: Object.create(HTMLInputElement.prototype)
});
6.
Custom Elements
• Lifecycle callbacks DEMO
– .createdCallback()
– .attachedCallback()
– .detachedCallback()
– .attributeChangedCallback()
var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() {
var div = document.createElement('div');
div.textContent = 'This is Custom Element';
this.appendChild(div);
};
var XComponent = document.registerElement('x-component', {
prototype: proto
});
7.
Custom Elements
• 与Templates and Shadow DOM结合使用
– 方便处理和复用
– template: 声明式的定义自定义元素的内容
– shadow dom: 限定内容中ID, class, style的作用域
15.
HTML Imports
• 导入文档中脚本在导入时会执行,但HTML标签并不会渲染,需要脚
本来处理
• 注意:导入文档中的document对象实际上指的是主文件的document对
象。
• 如何在主文档中引用导入文档中的document对象?
var link = document.querySelector('link[rel="import"]');
link.addEventListener('load', function(e) {
var importedDoc = link.import;
// importedDoc points to the document under
component.html
});
16.
HTML Imports
• 如何在导入文档中获取其document对象?
• 性能
– 重复资源只加载一次
– 利用工具合并html片断
var mainDoc = document.currentScript.ownerDocument;
// mainDoc points to the document under component.html