我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。

在JSF中,我可以这样做:

<ui:include src="b.xhtml" />

这意味着在.xhtml文件中,我可以包含b.xhtml。

我们如何在*.html文件中做到这一点?


当前回答

这些解决方案都不适合我的需要。我在寻找更像php的东西。在我看来,这个解决方案非常简单有效。

include.js - - - >

void function(script) {
    const { searchParams } = new URL(script.src);
    fetch(searchParams.get('src')).then(r => r.text()).then(content => {
        script.outerHTML = content;
    });
}(document.currentScript);

index . html - - - >

<script src="/include.js?src=/header.html">
<main>
    Hello World!
</main>
<script src="/include.js?src=/footer.html">

可以做一些简单的调整来创建include_once、require和require_once,它们可能都很有用,这取决于您正在做什么。下面是一个简短的例子。

include_once - - - >

var includedCache = includedCache || new Set();
void function(script) {
    const { searchParams } = new URL(script.src);
    const filePath = searchParams.get('src');
    if (!includedCache.has(filePath)) {
        fetch(filePath).then(r => r.text()).then(content => {
            includedCache.add(filePath);
            script.outerHTML = content;
        });
    }
}(document.currentScript);

希望能有所帮助!

其他回答

另一种方法是使用Fetch API和Promise

<html>
 <body>
  <div class="root" data-content="partial.html">
  <script>
      const root = document.querySelector('.root')
      const link = root.dataset.content;

      fetch(link)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          root.innerHTML = html;
        });
  </script>
 </body>
</html>

你试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在HTML DOM中)

<iframe src=“header.html” onload=“this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()”></iframe>

问候

您可以使用HTML Imports的填充(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)或简化的解决方案 https://github.com/dsheiko/html-import

例如,在你导入HTML块的页面上:

<link rel="html-import" href="./some-path/block.html" >

该块可以有自己的导入:

<link rel="html-import" href="./some-other-path/other-block.html" >

导入器用加载的HTML替换指令,就像SSI一样

这些指令将在你加载这个小JavaScript时自动提供:

<script async src="./src/html-import.js"></script>

它将在DOM准备就绪时自动处理导入。此外,它还公开了一个API,您可以使用该API手动运行、获取日志等等。享受:)

不要脸的插头一个库,我写了解这个。

https://github.com/LexmarkWeb/csi.js

<div data-include="/path/to/include.html"></div>

上面的代码将获取/path/to/include.html的内容,并用它替换div。

我强烈建议AngularJS的ng-include,不管你的项目是不是AngularJS。

<script src=".../angular.min.js"></script>

<body ng-app="ngApp" ng-controller="ngCtrl">

    <div ng-include="'another.html'"></div> 

    <script>
        var app = angular.module('ngApp', []);
        app.controller('ngCtrl', function() {});
    </script>

</body>

你可以从AngularJS中找到CDN(或下载Zip),更多信息可以从W3Schools中获取。