Web Components

Web Components是什麼


Web Components是一個彙集html,css,js的一個可複用組件。
這樣開發者就能夠在網絡上經過插件或組件的形式分享本身的代碼片斷(具備獨立的功能),也能夠理解成web組件或插件。css

Web Components的組成要素


  • 自定義元素
  • html模版
  • shadowDOM
  • HTML(組件)導入

shadowDOM是什麼


定義:瀏覽器將模板、樣式表、屬性、JavaScript代碼等,封裝成一個獨立的DOM元素。外部的設置沒法影響到其內部,而內部的設置也不會影響到外部,與瀏覽器處理原生網頁元素(好比<video>元素)的方式很像html

<!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.htmlweb

<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的方式引入app

圖片名稱

相關文章
相關標籤/搜索