首页 > 解决方案 > 如何将 HTML 导入 HTML 而不重复 head & body 标签?(如果可能,没有框架)

问题描述

我正在玩 HTML (, JavaScript & CSS) & 决定尝试将一个 HTML 从一个文件导入另一个文件,目标是我可以制作几个模块并将它们导入一个空的 HTML 页面,所以它们一起创建一个完整的工作和内容填充的 HTML 页面。

我更喜欢使用类似于导入脚本或样式表的方式:(
忽略 $ 符号)
$<script src="file.js"></script>

$<link rel="stylesheet" type="text/css" href="style.css">

问题是$<html>, <head> & <body>标签又被插入了,有什么好的方法可以解决这个问题吗?

我尝试了一些方法:$<object> & <embed>&
$<link rel="import" href="file.html">
我不想使用$<iframe>,因为我听说这是一个安全问题(是的,它现在不相关,但是如果我以后要真正使用这种方法,那么它将是重要的)。

我知道其他类似的问题,例如: Include another HTML file in a HTML file
但大多数答案都使用了我不想使用的外部框架,如 JQuery 或 Angular,我更喜欢使用纯 HTML 或/如果可能的话,还有 JavaScript 解决方案。

示例代码:

<p>"The import is working"</p>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>

  <body>
    <!-- Import code here (or in head if it for some reason is required) -->
  </body>

</html>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>

  <body>
    <p>"The import is working"</p>
  </body>

</html>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
      
  <body>
    <embed src="file.html">
  
      #Document <!-- I don't know what this means/function is, can someone explain? -->
      <html> <!-- Notice the double: html, head, meta & body -tags -->
        <head>
          <meta charset="UTF-8">
        </head>
        <body>
          <p>"The import is working"</p>
        </body>
      </html>
      
    </embed>
  </body>
  
</html>

标签: javascripthtml

解决方案


一段时间以来,我一直在尝试做同样的事情,而我想出的唯一解决方案涉及一些 JavaScript。当您导入 HTML 时, #document标签意味着它位于与呈现的不同的影子 DOM 中(我想,我不太了解这些东西)。无论如何,在导入之后,我最终不得不渲染元素并将其附加到 DOM。

<!-- Original HTML file -->
<html>

<head>
    <title>Title</title>
</head>

<body>
    <p> 
        Hello from original HTML.
    </p>
    <link id="importLink" rel="import" href="/path/to/import.html">
</body>
<script src="/path/to/renderImport.js"></script>
</html>

我的renderImport.js文件中有以下代码:

// renderImport.js
function renderImport() {
    let importLink = document.getElementById("importLink");
    let importedElement = importLink.import.querySelector('#import');

    document.body.appendChild(document.importNode(importedElement, true));
}

renderImport();

最后,import.html

<!-- import.html -->
<p id="import">Hello from the imported file</p>

这是在 Chrome 中。尽管您可能必须禁用 CORS。


推荐阅读