我有2个HTML文件,假设a.html和b.html.在a.html我想包括b.html.
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
Run Code Online (Sandbox Code Playgroud)
这意味着内部a.xhtml文件,我可以包括b.xhtml.
我们怎么能在*.html文件中做到这一点?
lol*_*olo 650
在我看来,最好的解决方案使用jQuery:
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
b.html:
<p>This is my include file</p>
Run Code Online (Sandbox Code Playgroud)
这个方法是解决我的问题的简单而干净的解决方案.
jQuery .load()文档就在这里.
mha*_*sch 141
从上面扩展lolo的答案,如果你需要包含很多文件,这里有一点自动化:
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = 'views/' + $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
然后在html中包含一些内容:
<div data-include="header"></div>
<div data-include="footer"></div>
Run Code Online (Sandbox Code Playgroud)
其中包括文件views/header.html和views/footer.html
Taf*_*soh 136
我的解决方案类似于上面的lolo.但是,我通过JavaScript的document.write而不是使用jQuery插入HTML代码:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
Run Code Online (Sandbox Code Playgroud)
我反对使用jQuery的原因是jQuery.js的大小约为90kb,我希望尽可能减少加载的数据量.
为了在没有太多工作的情况下获取正确转义的JavaScript文件,您可以使用以下sed命令:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Run Code Online (Sandbox Code Playgroud)
或者只是使用下面在Github上作为Gist发布的方便的bash脚本,自动完成所有必要的工作,转换b.html为b.js:https:
//gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Greg Minshall对改进的sed命令的信用也逃脱了反斜杠和单引号,这是我原来的sed命令没有考虑的.
小智 84
通过Html5rocks教程 和聚合物项目导出 HTML5导入
例如:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Run Code Online (Sandbox Code Playgroud)
Mic*_*arr 57
我编写的库的无耻插件解决了这个问题.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
Run Code Online (Sandbox Code Playgroud)
以上将取内容/path/to/include.html并替换div它.
Web*_*don 42
一个简单的服务器端include指令包含在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
Run Code Online (Sandbox Code Playgroud)
Ale*_*cić 33
一个非常古老的解决方案我当时满足了我的需求,但这里是如何做到符合标准的代码:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
Run Code Online (Sandbox Code Playgroud)
bjb*_*568 33
不需要脚本.不需要在服务器端做任何花哨的东西(这可能是更好的选择)
<iframe src="/path/to/file.html" seamless></iframe>
Run Code Online (Sandbox Code Playgroud)
由于旧浏览器不支持无缝,您应该添加一些css来修复它:
iframe[seamless] {
border: none;
}
Run Code Online (Sandbox Code Playgroud)
请记住,对于不支持无缝的浏览器,如果单击iframe中的链接,它将使框架转到该URL,而不是整个窗口.解决这个问题的方法是拥有所有链接target="_parent",浏览器支持"足够好".
Bur*_*kan 19
这是我的内联解决方案:
(() => {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, i => {
let filePath = i.getAttribute('src');
fetch(filePath).then(file => {
file.text().then(content => {
i.insertAdjacentHTML('afterend', content);
i.remove();
});
});
});
})();Run Code Online (Sandbox Code Playgroud)
<p>FOO</p>
<include src="a.html">Loading...</include>
<p>BAR</p>
<include src="b.html">Loading...</include>
<p>TEE</p>Run Code Online (Sandbox Code Playgroud)
小智 16
作为替代方案,如果您可以访问服务器上的.htaccess文件,则可以添加一个简单的指令,允许在以.html扩展名结尾的文件上解析php.
RemoveHandler .html
AddType application/x-httpd-php .php .html
Run Code Online (Sandbox Code Playgroud)
现在您可以使用简单的PHP脚本来包含其他文件,例如:
<?php include('b.html'); ?>
Run Code Online (Sandbox Code Playgroud)
小智 13
如果需要包含来自某个文件的html内容,则以下工作:例如,以下行将在OBJECT定义发生的位置包含piece_to_include.html的内容.
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
Run Code Online (Sandbox Code Playgroud)
参考:http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
这对我有所帮助.从添加的HTML代码块b.html来a.html,这应该进入head的标签a.html:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Run Code Online (Sandbox Code Playgroud)
然后在body标签中,使用唯一的id和javascript块b.html将容器加载到容器中,如下所示:
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
Run Code Online (Sandbox Code Playgroud)
在w3.js中包含这样的作品:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
Run Code Online (Sandbox Code Playgroud)
我知道这是一个非常古老的帖子,所以当时没有一些方法可用.但这是我非常简单的看法(根据Lolo的回答).
它依赖于HTML5 data-*属性,因此非常通用,因为它使用jQuery的for-each函数来使每个.class匹配"load-html"并使用其各自的'data-source'属性来加载内容:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
您可以使用HTML Imports(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)的polyfill ,或者简化的解决方案 https://github.com/dsheiko/html-import
例如,在页面上导入HTML块,如下所示:
<link rel="html-import" href="./some-path/block.html" >
Run Code Online (Sandbox Code Playgroud)
该块可能有自己的导入:
<link rel="html-import" href="./some-other-path/other-block.html" >
Run Code Online (Sandbox Code Playgroud)
导入器将指令替换为加载的HTML,与SSI非常相似
加载这个小JavaScript后,这些指令将自动提供:
<script async src="./src/html-import.js"></script>
Run Code Online (Sandbox Code Playgroud)
当DOM准备就绪时,它将处理导入.此外,它还公开了一个可用于手动运行,获取日志等的API.请享用 :)
这是我使用 Fetch API 和异步函数的方法
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
Run Code Online (Sandbox Code Playgroud)
另一种使用 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>
Run Code Online (Sandbox Code Playgroud)
我创建了以下类似于 JSF 的Web 组件
<ui-include src="b.xhtml"><ui-include>
Run Code Online (Sandbox Code Playgroud)
您可以将其用作页面内的常规 html 标签(包含片段 js 代码后)
<ui-include src="b.xhtml"><ui-include>
Run Code Online (Sandbox Code Playgroud)
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})Run Code Online (Sandbox Code Playgroud)
ui-include { margin: 20px } /* example CSS */Run Code Online (Sandbox Code Playgroud)
(当你第一次去这里并按下按钮让你的计算机临时访问 cors-anywhere时,stackoverflow 代码片段会更好地工作(加载整个页面,而不仅仅是消息) )
小智 7
使用includeHTML(最小的 js-lib:约 150 行)
通过 HTML 标签加载 HTML 部分(纯 js)
支持加载:异步/同步,任何深度递归包括
支持的协议:http://、https://、file:///
支持的浏览器:IE 9+、FF、Chrome(也可能是其他)
1.将includeHTML插入 HTML 文件的 head 部分(或 body 关闭标记之前):
<script src="js/includeHTML.js"></script>
Run Code Online (Sandbox Code Playgroud)
2.任何地方使用includeHTML作为HTML标签:
<div data-src="header.html"></div>
Run Code Online (Sandbox Code Playgroud)
大多数解决方案都有效,但它们与jquery存在问题:
问题是以下代码$(document).ready(function () { alert($("#includedContent").text()); }警报,而不是警告包含的内容.
我写下面的代码,在我的解决方案中,您可以访问$(document).ready功能中包含的内容:
(关键是同步加载包含的内容).
index.htm:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
Run Code Online (Sandbox Code Playgroud)
html5rocks.com有一个关于这方面的非常好的教程,这可能有点晚了,但我自己并不知道它的存在。w3schools 也有一种方法可以使用他们名为 w3.js 的新库来做到这一点。问题是,这需要使用 Web 服务器和 HTTPRequest 对象。您实际上无法在本地加载这些并在您的计算机上测试它们。不过,您可以使用顶部 html5rocks 链接上提供的 polyfill,或者按照他们的教程进行操作。使用一点 JS 魔法,你可以做这样的事情:
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
Run Code Online (Sandbox Code Playgroud)
这将创建链接(如果已设置,可以更改为所需的链接元素),设置导入(除非您已经拥有它),然后附加它。然后它将从那里获取并解析 HTML 中的文件,然后将其附加到 div 下的所需元素。从附加元素到您正在使用的链接,这一切都可以更改以满足您的需求。我希望这会有所帮助,如果不使用 jQuery 或 W3.js 等库和框架而出现更新、更快的方法,那么现在可能已经无关紧要了。
更新:这将引发错误,指出本地导入已被 CORS 策略阻止。由于深层网络的特性,可能需要访问深层网络才能使用它。(意思是没有实际用途)
小智 5
您是否尝试过 iFrame 注入?
它在文档中注入 iFrame 并删除自己(它应该在 HTML DOM 中)
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
问候
这些解决方案都不适合我的需求。我一直在寻找更像 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);
Run Code Online (Sandbox Code Playgroud)
index.html->
<script src="/include.js?src=/header.html">
<main>
Hello World!
</main>
<script src="/include.js?src=/footer.html">
Run Code Online (Sandbox Code Playgroud)
可以进行简单的调整来创建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);
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
1353446 次 |
| 最近记录: |