<link rel="import" href="header.html">
<link rel="import" href="footer.html">
<script>
var link = document.querySelector('link[href*="header"]');
var template = link.import.querySelector('template');
var clone = document.importNode(template.content, true);
document.querySelector('#nav').appendChild(clone);
</script>
<script>
var link = document.querySelector('link[href*="footer"]');
var template = link.import.querySelector('template');
var clone = document.importNode(template.content, true);
document.querySelector('.footer').appendChild(clone);
</script>
只有基于Chromium / Blink的浏览器已经发布了<link rel=import>
HTML Imports支持。 Firefox不支持HTML Imports unless you enable the dom.webcomponents.enabled
flag:
Firefox不会发布HTML Imports。有关更多信息,请参阅此Hacks blog post。您仍然可以通过启用dom.webcomponents.enabled标志在Firefox中使用HTML Imports。如果您不想启用该标记,则可以使用Google的webcomponents.js等polyfill。
目前的HTML Imports spec基本上已经死了,自2016年2月以来刚刚处于工作草案状态时停滞不前,并且不会在W3C标准化轨道上进一步推进。
因此,没有其他浏览器会实现旧的HTML Imports规范。相反,在某些时候,将开发一个新的规范 - 一个挂钩到ES6 Modules和<script type=module>
“module scripts” as now defined in the HTML spec的基础机制。
我建议使用来自HTML Imports polyfill的文件html-imports.min.js而不是用户浏览器上未启用的firefox标志,其实现已过时(并且可能导致与其他polyfill对自定义元素或shadow DOM的混淆)。
此外,使用polyfill时,请记住HTML导入将始终为async
,因此在使用HTMLImportsLoaded
属性的内容之前,您必须等待link.import
事件。
<script src="html-imports.min.js"></script>
<link rel="import" href="header.html">
<link rel="import" href="footer.html">
<script>
document.addEventListener( 'HTMLImportsLoaded', function ()
{
var link = document.querySelector('link[href*="header"]');
var template = link.import.querySelector('template');
var clone = document.importNode(template.content, true);
document.querySelector('#nav').appendChild(clone);
link = document.querySelector('link[href*="footer"]');
template = link.import.querySelector('template');
clone = document.importNode(template.content, true);
document.querySelector('.footer').appendChild(clone);
} )
</script>