javascript - 如何将 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>
- 实际结果(带有
$<object>
或$<embed
>),(至少如 Firefox 检查元素工具所示):
<!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>
解决方案
一段时间以来,我一直在尝试做同样的事情,而我想出的唯一解决方案涉及一些 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。
推荐阅读
- python - 如何在 Python 中同一类对象的 2 个实例中触发方法?
- javascript - Await 不使用 firebase 批处理功能等待
- flutter - Flutter:当 InkWell() 的子元素是容器时如何修复 Tap 效果
- javascript - 创建钩子时出错:“ReferenceError:未定义回声”
- python - 将 HuggingFace Trainer 与 Ray Tune 一起使用时“无法腌制 _thread.RLock 对象”
- wordpress - 如何通过flutter访问http本地woocommerce api localhost
- azure - 如何更改 Azure DSVM 虚拟机上的默认启动文件夹 jupyter hub
- openssl - 为 ARM64 构建 Zeek 失败 CMake 错误 Openssl
- html - 如何在 vs 代码中的 jupyter 上的浏览器中查看绘图
- html - 当悬停另一个具有不同父级的 div 时,CSS 显示 div