Web Components 包含了多种不同的技术。你可以把Web Components当做是用一系列的Web技术创建的、可重用的用户界面组件的统称。Web Components使开发人员拥有扩展浏览器标签的能力,可以自由的进行定制组件。但截至本文时间,Web Components依然是W3C工作组的一个草案,并为被正式纳入标准,但这并不妨碍我们去学习它。
有时候关于Web Components和谷歌的plymer之间可能会存在一些困惑,简介而论,Polymer是基于Web Components技术的一个框架,你当然可以在不适用其的情况下开发Web Components
Web Components并没有被所有浏览器来实现(截止2017年chrome已经完全支持,其实其他标准浏览器现在也都支持),因此如果在不支持的浏览器上使用Web Components,
应该使用由google polymer开发的 polyfills来达到目的。使用之前最好通过Are We Componentized Yet查看浏览器兼容性。
何为Web组件?Web组件相对于Web开发者来说并不陌生,Web组件是一套封装好的HTML,CSS,以及JavaScript,它最大的特点就是可复用。基本在每一个网站上我们都可以看到各式各样的组件,例如下拉菜单、按钮、图片滚播、日历控件等。慢着,既然我们已经可以实现web组件的封装,那Web Component这家伙出现的意义是什么呢?Web Component回答道:“你们的实现方式不够优雅也不够完美,还是看看我的吧”。
因为当我们使用各种编程技巧对组件进行封装时,一个无法规避的事实是,组件的内部是可被访问和影响的,例如我们对样式表进行改动时经常会担心影响到页面组件的样式。而通过Web Component封装出来的组件,我们可以选择让组件的内部隐藏起来,也就是说,组件内部是与世隔绝的!
一种可以允许开发者在document中定义并使用的新的dom元素类型,即自定义元素
模板没什么可说了,在标准实现之前其实我们一直都在用js来实现该方式
一种可以在document下组合多个同级别并且可以项目作用的DOM树的方法,因此可以更好完善DOM的构成
一种允许一个html文档在别的htmldocuments中包含和复用的方法
未完待续。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
1 2 3 4 5 6 7 8 9 10 11 | //index.html <!DOCTYPE> <html> <head> <title>webcomponent</title> <link rel="import" href="./components/helloword.html" /> </head> <body> <hellow-world></hellow-world> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //helloworld.html <template> <style> .coloured { color: red; } </style> <p>the first webcompnent is <strong class="coloured">Hello World</strong></p> </template> <script> (function() { // Creates an object based in the HTML Element prototype // 基于HTML Element prototype 创建obj var element = Object.create(HTMLElement.prototype); // 获取特tmplate的内容 var template = document.currentScript.ownerDocument.querySelector('template').content; // element创建完成之后的回调 element.createdCallback = function() { // 创建 shadow root var shadowRoot = this.createShadowRoot(); // 向root中加入模板 var clone = document.importNode(template, true); shadowRoot.appendChild(clone); }; document.registerElement('hellow-world', { prototype: element }); }()); </script> |
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Web Components之Custom Elements组件开发"
最新评论