在另一个 html 文件中包含 html

Include html in another html file

我有一个 html "head" 模板和一个导航模板,我想将它们包含在我站点的所有其他 html 文件中。 我发现这个 post:

Include another HTML file in a HTML file

我的问题是...如果我想包含 header 怎么办?

例如,我有以下文件结构:

 /var/www/includes/templates/header.html
                             navigation.html

header.html 可能看起来像这样:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Test Portal</title>

 </head>

在这种情况下,我是否仍可以按照另一个 post 中的示例创建一个 div 并通过 jquery 填充 div?

方法一:

我认为最好的方法是使用 jQuery 将 html content/file 包含到另一个 html 文件中。

您可以简单地包含 jQuery.js 并使用 $("#DivContent").load("yourFile.html");

加载 HTML 文件

例如

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#DivContent").load("another_file.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="DivContent"></div>
  </body> 
</html>

方法二:

没有此类标签可用于包含该文件,但有一些第三方方法可用,例如:

<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>

<body>

<div w3-include-html="content.html"></div> 

<script>
w3IncludeHTML();
</script>

</body>
</html>

方法三:

有些人还使用了服务器端包含 (SSI):

<!--#include virtual="a.html" --> 

使用 HTML <iframe> 标签。

我遇到过类似的问题,然后我用了

<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>

我需要包含很多文件。所以我创建了以下脚本:

<script>
  $(function(){
    $('[id$="-include"]').each(function (e){
        $(this).load("includes\" + $(this).attr("id").replace("-include", "") +  ".html");
    });
  });
</script>

使用div,例如,为插入放置一个占位符。

<div id="example-include"></div>

为我需要包含的所有文件创建了文件夹 "includes"。已创建文件 "example.html"。 它适用于任意数量的包含。您只需使用命名约定并将所有包含的文件放在正确的文件夹中。

使用<object>标签:

<object data="filename.html"></object>

对于任何对 Web 组件方法感兴趣的人:

<html-include src="my-html.html"></html-include>

以及对应的JS:

class HTMLInclude extends HTMLElement {
  constructor() {
    super();
    this.innerHTML = "Loading...";
    this.loadContent();
  }

  async loadContent() {
    const source = this.getAttribute("src");
    if (!source) {
      throw new Error("No src attribute given.");
    }
    const response = await fetch(source);
    if (response.status !== 200) {
      throw new Error(`Could not load resource: ${source}`);
    }
    const content = await response.text();
    this.innerHTML = content;
  }
}

window.customElements.define("html-include", HTMLInclude);

请注意,可以使用阴影做一些不错的事情 DOM 以确保加载内容的样式不会影响外部页面。

上面的代码是相当“现代”的 JS,如果不进行一些 polyfills/babel 转换,您可能不想直接使用上面的代码。

这类似于另一个自定义标签解决方案,但这个解决方案使用开始和结束标签之间的文本作为包含 path/url。另一个解决方案使用 src 属性。

<html-include> ./partials/toolbar.html </html-include>

元素实现有点棘手:

# -- ./js/html-include.js --

class HTMLInclude extends HTMLElement {
    constructor(src) {
        super();
        this.attachShadow({mode: "open"});
        if (src) { 
            this.textContent = src;
        }
        setTimeout(() => this._load());
    }
    async _load() {
        let src = this.textContent.trim();

        if (!src) {
            throw new Error("URL missing between <html-import> tags.");
        } 
        let rsp = await fetch(src);

        if (rsp.status != 200) {
            throw new Error(`Failed to load file (${src}) for <html-import>.`);
        }
        this.shadowRoot.innerHTML = await rsp.text();
    }
}
customElements.define("html-include", HTMLInclude);

setTimeout() 是必要的,因为 this.textContent,如果过早访问,可能会包含页面的所有前面的文本(在 Chrome/Chromium 上看到)。推迟访问可以解决这个问题。

这是合并到页面中的样子:

<html>
    <head>
        <link rel="stylesheet" href="./css/index.css">
        <script type="text/javascript" src="./js/html-include.js"></script>
    </head>
    <body>
        <html-include> ./partials/toolbar.html   </html-include>
        <html-include> ./partials/side-menu.html </html-include>
        <html-include> ./partials/statusbar.html </html-include>
    </body>
</html>

CSS 样式应正确应用于新导入的 HTML.

此元素也可以通过将 URL 传递给导入文件从 JS 创建。

let wgthost = document.getElementById("tgt");
wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));