Web Components是一個彙集html,css,js的一個可複用組件。
這樣開發者就能夠在網絡上經過插件或組件的形式分享本身的代碼片斷(具備獨立的功能),也能夠理解成web組件或插件。css
定義:瀏覽器將模板、樣式表、屬性、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>
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>
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>
shadow.html網絡
<link rel="import" href="temp.html"/> <link rel="import" href="temp1.html"/>
直接經過link的方式引入app