2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

Web Components

Web Components是什么


Web Components是一个聚集html,css,js的一个可复用组件。
这样开发者就可以在网络上通过插件或组件的形式分享自己的代码片段(具有独立的功能),也可以理解成web组件或插件。

Web Components的组成要素


  • 自定义元素
  • html模版
  • shadowDOM
  • HTML(组件)导入

shadowDOM是什么


定义:浏览器将模板、样式表、属性、JavaScript代码等,封装成一个独立的DOM元素。外部的设置无法影响到其内部,而内部的设置也不会影响到外部,与浏览器处理原生网页元素(比如<video>元素)的方式很像

<!DOCTYPE html>
<html>
  <head>
     <title>Shadow DOM</title>
  
     <style>
       button {
          font: 18px Century Schoolbook;
          border: thin solid gray;
          background: rgba(200, 200, 200, 0.5);
          padding: 10px;
       }
     </style>
  </head>
  
  <body>
       
    <div class="container"></div>
 
    <script>
      var host = document.querySelector('.container');
      var root = host.createShadowRoot();
      root.innerHTML = '<p>How <em>you</em> doin?</p>'
    </script>
  </body>
</html>
图片名称

独立的组件


组件有两种形式

  • 非shadowDOM组件
  • shadowDOM组件

非shadowDOM组件

temp.html

<script>
  var proto = Object.create(HTMLElement.prototype);
 
  proto.createdCallback = function() {
    var name = this.getAttribute('name');
    this.innerHTML = '欢迎来到web组件, <b>' +
                     (name || '?') + '</b>';
  };
 
  document.registerElement('say-hi', {prototype: proto});
</script>

shadowDOM组件

temp2.html

<template id="t">
  <style>
    ::content > * {
      color: red;
    }
  </style>
  <span>I'm a shadow-element using Shadow DOM!</span>
  <content></content>
</template>
 
<script>
  (function() {
    // 指向被加载的网页
    var importDoc = document.currentScript.ownerDocument;
 
    // 定义并登记<shadow-element>
    var proto2 = Object.create(HTMLElement.prototype);
 
    proto2.createdCallback = function() {
      var template = importDoc.querySelector('#t');
      var clone = document.importNode(template.content, true);
      var root = this.createShadowRoot();
      root.appendChild(clone);
    };
 
    document.registerElement('shadow-element', {prototype: proto2});
  })();
</script>

知识点

  • HTMLElement.prototype:为自定义注册的元素指定原型
  • createdCallback:是实例生成时触发的hook
  • registerElement:注册自定义组件

组件引入


shadow.html

<link rel="import" href="temp.html"/>
<link rel="import" href="temp1.html"/>

直接通过link的方式引入

图片名称

posted on 2017-08-14 22:56  qize  阅读(708)  评论(0编辑  收藏  举报

导航