<style>
…
</style>
<div id="container">
<img src="http://webcomponents.org/img/logo.svg">
<content select="h1"></content>
</div>
</template>
<script>
// This element will be registered to index.html
// Because `document` here means the one in index.html
var XComponent = document.registerElement(‘x-component’, {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var root = this.createShadowRoot();
var template = document.querySelector(‘#template’);
var clone = document.importNode(template.content, true);
root.appendChild(clone);
}
}
})
});
</script>
index.html
XML/HTML Code复制内容到剪贴板
…
<link rel="import" href="x-component.html">
</head>
<body>
<x-component>
<h1>This is Custom Element</h1>
</x-component>
…
注意,因为x-component.html 中的document 对象跟index.html的一样,你没必要再写一些棘手的代码,它会自动为你注册。
支持的浏览器
Chrome 和 Opera提供对HTML导入的支持,Firefox要在2014年12月后才支持(Mozilla表示Firefox不计划在近期提供对HTML导入的支持,声称需要首先了解ES6的模块是怎样实现的)。
你可以去chromestatus.com或caniuse.com查询浏览器是否支持HTML导入。想要在其他浏览器上使用HTML导入,可以用webcomponents.js(原名platform.js)。
相关资源
HTML导入就介绍这么多了。如果你想学更多关于HTML导入的知识,请前往:









