获取错误 link.import 在 Firefox 中为空

getting error link.import is null in firefox

<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>
我删除了页眉和页脚,我必须调用所有页面,我正在使用 HTML5,但页眉和页脚仅在 Google Chrome 浏览器、FireFox 和 Safari 中显示不显示页眉和页脚并给出类似 TypeError: link.import is null

的错误

只有 Chromium/Blink-based 浏览器提供了 <link rel=import> HTML 导入支持。 Firefox 不支持 HTML 导入 unless you enable the dom.webcomponents.enabled flag:

Firefox will not ship HTML Imports. See this Hacks blog post for more information. You can still use HTML Imports in Firefox by enabling the dom.webcomponents.enabled flag. If you don't want to enable the flag, you can use a polyfill such as Google's webcomponents.js.

目前的 HTML Imports spec 在这一点上基本上已经死了,自 2016 年 2 月以来一直处于工作草案状态,并且不会沿着 W3C 标准化轨道进一步推进。

所以没有其他浏览器会实施旧的 HTML 导入规范。相反,在某个时候将开发一个新的规范——一个挂钩到 ES6 Modules and the underlying machinery of <script type=module> “module scripts” as now defined in the HTML spec.

的规范

我建议使用 HTML Imports polyfill 中的文件 html-imports.min.js 而不是未启用的 firefox 标志您用户的浏览器及其实现已过时(并可能导致与自定义元素或阴影的其他 polyfill 冲突 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>