在超文本标记语言文件中包含另一个超文本标记语言文件

我有两个超文本标记语言文件,假设a.htmlb.html。在a.html中,我想包含b.html

在JSF中,我可以这样做:

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

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

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

1951857 次浏览

作为替代方案,如果您可以访问服务器上的. htaccess文件,您可以添加一个简单的指令,允许在以. html扩展名结尾的文件上解释php。

RemoveHandler .html
AddType application/x-httpd-php .php .html

现在,您可以使用简单的php脚本来包含其他文件,例如:

<?php include('b.html'); ?>

在我看来,最好的解决方案是使用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>

b.html

<p>This is my include file</p>

这个方法对我的问题是一个简单而干净的解决方案。

jQuery.load()留档是这里

我的解决方案类似于上面的lolo。但是,我通过JavaScript的document.write插入超文本标记语言代码,而不是使用jQuery:

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>

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>\
\
');

我反对使用jQuery的原因是jQuery.js大小约为90kb,并且我希望保持要加载的数据量尽可能小。

为了在不做太多工作的情况下获得正确转义的JavaScript文件,您可以使用以下ses命令:

sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html

或者只需使用以下方便的bash脚本作为Gist发布在Github上,它可以自动执行所有必要的工作,将b.html转换为b.jshttps://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

归功于格雷格·明希尔,因为改进的ses命令也转义了反斜杠和单引号,这是我最初的ses命令没有考虑的。

或者对于支持模板文字的浏览器,以下内容也有效:

b.js:

document.write(`


<h1>Add your HTML code here</h1>


<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>


`);

一个简单的服务器端包含指令,用于包含在同一文件夹中找到的另一个文件,如下所示:

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

你也可以试试:

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

一个非常古老的解决方案我当时确实满足了我的需求,但以下是如何做到符合标准的代码:

<!--[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]-->

要插入命名文件的内容:

<!--#include virtual="filename.htm"-->

我来到这个主题是为了寻找类似的东西,但与lolo提出的问题有点不同。我想构建一个超文本标记语言页面,包含指向其他页面的字母顺序菜单,其他页面可能存在也可能不存在,它们创建的顺序可能不是字母顺序(甚至不是数字)。此外,像Tafkadasoh一样,我不想用jQuery膨胀网页。在研究了这个问题并实验了几个小时后,这是对我有效的方法,并添加了相关评论:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
<meta name="Author" content="me">
<meta copyright="Copyright" content= "(C) 2013-present by me" />
<title>Menu</title>


<script type="text/javascript">
<!--
var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
var dat = new Array();
var form, script, write, str, tmp, dtno, indx, unde;


/*
The "F000" and similar variables need to exist/be-declared.
Each one will be associated with a different menu item,
so decide on how many items maximum you are likely to need,
when constructing that listing of them.  Here, there are 20.
*/




function initialize()
{ window.name="Menu";
form = document.getElementById('MENU');
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = str.substr(tmp);
script = document.createElement('script');
script.type = 'text/javascript';
script.src = str + ".js";
form.appendChild(script);
}


/*
The for() loop constructs some <script> objects
and associates each one with a different simple file name,
starting with "000.js" and, here, going up to "019.js".
It won't matter which of those files exist or not.
However, for each menu item you want to display on this
page, you will need to ensure that its .js file does exist.


The short function below (inside HTML comment-block) is,
generically, what the content of each one of the .js files looks like:
<!--
function F000()
{ return ["Menu Item Name", "./URLofFile.htm", "Description string"];
}
-->


(Continuing the remarks in the main menu.htm file)
It happens that each call of the form.appendChild() function
will cause the specified .js script-file to be loaded at that time.
However, it takes a bit of time for the JavaScript in the file
to be fully integrated into the web page, so one thing that I tried,
but it didn't work, was to write an "onload" event handler.
The handler was apparently being called before the just-loaded
JavaScript had actually become accessible.


Note that the name of the function in the .js file is the same as one
of the pre-defined variables like "F000".  When I tried to access
that function without declaring the variable, attempting to use an
"onload" event handler, the JavaScript debugger claimed that the item
was "not available".  This is not something that can be tested-for!
However, "undefined" IS something that CAN be tested-for.  Simply
declaring them to exist automatically makes all of them "undefined".
When the system finishes integrating a just-loaded .js script file,
the appropriate variable, like "F000", will become something other
than "undefined".  Thus it doesn't matter which .js files exist or
not, because we can simply test all the "F000"-type variables, and
ignore the ones that are "undefined".  More on that later.


The line below specifies a delay of 2 seconds, before any attempt
is made to access the scripts that were loaded.  That DOES give the
system enough time to fully integrate them into the web page.
(If you have a really long list of menu items, or expect the page
to be loaded by an old/slow computer, a longer delay may be needed.)
*/


window.setTimeout("BuildMenu();", 2000);
return;
}




//So here is the function that gets called after the 2-second delay
function BuildMenu()
{ dtno = 0;    //index-counter for the "dat" array
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = "F" + str.substr(tmp);
tmp = eval(str);
if(tmp != unde) // "unde" is deliberately undefined, for this test
dat[dtno++] = eval(str + "()");
}


/*
The loop above simply tests each one of the "F000"-type variables, to
see if it is "undefined" or not.  Any actually-defined variable holds
a short function (from the ".js" script-file as previously indicated).
We call the function to get some data for one menu item, and put that
data into an array named "dat".


Below, the array is sorted alphabetically (the default), and the
"dtno" variable lets us know exactly how many menu items we will
be working with.  The loop that follows creates some "<span>" tags,
and the the "innerHTML" property of each one is set to become an
"anchor" or "<a>" tag, for a link to some other web page.  A description
and a "<br />" tag gets included for each link.  Finally, each new
<span> object is appended to the menu-page's "form" object, and thereby
ends up being inserted into the middle of the overall text on the page.
(For finer control of where you want to put text in a page, consider
placing something like this in the web page at an appropriate place,
as preparation:
<div id="InsertHere"></div>
You could then use document.getElementById("InsertHere") to get it into
a variable, for appending of <span> elements, the way a variable named
"form" was used in this example menu page.


Note: You don't have to specify the link in the same way I did
(the type of link specified here only works if JavaScript is enabled).
You are free to use the more-standard "<a>" tag with the "href"
property defined, if you wish.  But whichever way you go,
you need to make sure that any pages being linked actually exist!
*/


dat.sort();
for(indx=0; indx<dtno; indx++)
{ write = document.createElement('span');
write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] +
"', 'Menu');\" style=\"color:#0000ff;" +
"text-decoration:underline;cursor:pointer;\">" +
dat[indx][0] + "</a> " + dat[indx][2] + "<br />";
form.appendChild(write);
}
return;
}


// -->
</script>
</head>


<body onload="initialize();" style="background-color:#a0a0a0; color:#000000;


font-family:sans-serif; font-size:11pt;">
<h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;MENU
<noscript><br /><span style="color:#ff0000;">
Links here only work if<br />
your browser's JavaScript<br />
support is enabled.</span><br /></noscript></h2>
These are the menu items you currently have available:<br />
<br />
<form id="MENU" action="" onsubmit="return false;">
<!-- Yes, the <form> object starts out completely empty -->
</form>
Click any link, and enjoy it as much as you like.<br />
Then use your browser's BACK button to return to this Menu,<br />
so you can click a different link for a different thing.<br />
<br />
<br />
<small>This file (web page) Copyright (c) 2013-present by me</small>
</body>
</html>

不需要脚本。不需要在服务器端做任何花哨的事情(尽管这可能是更好的选择)

<iframe src="/path/to/file.html" seamless></iframe>

由于旧浏览器不支持无缝,您应该添加一些css来修复它:

iframe[seamless] {
border: none;
}

请记住,对于不支持无缝的浏览器,如果您单击ifram中的链接,它将使框架转到该URL,而不是整个窗口。一种解决方法是让所有链接都有target="_parent",尽管浏览器支持“足够好”。

阿萨里的回答(第一个!)太有说服力了!很好!

但是如果你想传递要作为URL参数包含的页面名称,这篇文章有一个非常好的解决方案可以结合使用:

http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html

所以它变成了这样:

您的URL:

www.yoursite.com/a.html?p=b.html

a.html代码现在变成:

<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>


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

这对我来说非常有用! 希望有帮助:)

PHP是一种服务端脚本语言。它可以做很多事情,但一个流行的用途是在您的页面中包含超文本标记语言文档,与SSI非常相似。与SSI一样,这是一种服务端技术。如果您不确定您的网站上是否有PHP功能,请联系您的托管提供商。

以下是一个简单的PHP脚本,可用于在任何启用PHP的网页上包含超文本标记语言片段:

将站点常用元素的超文本标记语言保存为单独的文件。例如,导航部分可能保存为navigation.html或navigation.php. 使用以下PHP代码在每个页面中包含该超文本标记语言。

<?php require($DOCUMENT_ROOT . "navigation.php"); ?>

在要包含文件的每个页面上使用相同的代码。 确保将高亮的文件名更改为包含文件的名称和路径。

无耻的一个库插件,我写的解决这个。

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

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

上面将采用/path/to/include.html的内容并将div替换为它。

签出HTML5导入通过Html5岩石教程 聚合物项目

例如:

<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>

如果需要包含某些文件中的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...

参考:http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4

大多数解决方案都有效,但它们与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>

include.inc

<div id="test">
There is no issue between this solution and jquery.
</div>

github上的jQuery包含插件

使用jQuery你需要导入库

我建议你使用php

<?php
echo"<html>
<body>";
?>
<?php
include "b.html";
?>
<?php
echo" </body>
</html>";
?>

b.html

<div>hi this is ur file :3<div>

如果你使用像django/bootle这样的框架,他们通常会提供一些模板引擎。 假设你使用的是瓶子,默认的模板引擎是简单模板引擎。 下面是纯html文件

$ cat footer.tpl
<hr> <footer>   <p>&copy; stackoverflow, inc 2015</p> </footer>

您可以将footer.tpl包含在主文件中,例如:

$ cat dashboard.tpl
%include footer

除此之外,您还可以将参数传递给dashborard.tpl.

目前还没有直接的超文本标记语言解决方案。即使是超文本标记语言导入(永久的在草案)也不会做这件事,因为导入!=包含,无论如何都需要一些JS魔法。
我最近写了一个VanillaJS脚本,只是为了将超文本标记语言包含到超文本标记语言中,没有任何并发症。

只要放在你的a.html

<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>

它是open-source,可能会给出一个想法(我希望)

这是一篇很棒的文章,您可以实现通用库,只需使用下面的代码在一行中导入任何超文本标记语言文件。

<head>
<link rel="import" href="warnings.html">
</head>

你也可以试试谷歌聚合物

扩展Lolo的回答,如果您必须包含大量文件,这里会更加自动化。使用此JS代码:

$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})

然后在html中包含一些内容:

<div data-include="header"></div>
<div data-include="footer"></div>

其中包括文件views/header.htmlviews/footer.html

好吧,如果你想做的只是将文本从一个单独的文件放入你的页面(文本中的标签也应该有效),你可以这样做(主页上的文本样式-test.html-应该仍然有效):

test.html

<html>
<body>
<p>Start</p>


<p>Beginning</p>


<div>
<script language="JavaScript" src="sample.js"></script>
</div>


<p>End</p>


</body>
</html>

sample.js

var data="Here is the imported text!";
document.write(data);

毕竟,您总是可以自己重新创建您想要的超文本标记语言。需要服务器端脚本来从另一个文件中获取文本,除非您想做更多的事情。

无论如何,我开始使用它是为了使它,如果我更新许多超文本标记语言文件中常见的描述,我只需要更新一个文件(.js文件),而不是每个包含文本的超文本标记语言文件。

因此,总而言之,与其导入.html文件,更简单的解决方案是导入一个.js文件,其中包含变量中.html文件的内容(并将内容写入调用脚本的屏幕)。

谢谢提问。

你可以这样使用JavaScript的库jQuery:

超文本标记语言:

<div class="banner" title="banner.html"></div>

js:

$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});

请注意,banner.html应位于您其他页面所在的同一域下,否则您的网页将由于跨域资源共享策略而拒绝banner.html文件。

此外,请注意,如果您使用JavaScript加载内容,Google将无法对其进行索引,因此出于SEO原因,这并不是一种很好的方法。

基于的答案https://stackoverflow.com/a/31837264/4360308 我已经用Nodejs(+Express+啦啦队)实现了这个功能,如下所示:

超文本标记语言(index.html)

<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>

JS

function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}


function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}

append->将内容包含到div中

替换->替换div

您可以根据相同的设计轻松添加更多行为

html5rocks.com在这方面有一个非常好的教程,这可能有点晚了,但我自己不知道这是什么。w3学校也有一种使用他们的新库来做到这一点的方法,名为w3.js.问题是,这需要使用Web服务器和HTTPRequest对象。你不能实际在本地加载这些并在你的机器上测试它们。不过,你可以做的是使用顶部html5Rocks链接上提供的Poly填充,或者按照他们的教程进行操作。借助一点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);
}

这将使链接(如果已经设置,可以更改为所需的链接元素),设置导入(除非您已经拥有它),然后附加它。然后它将从那里获取并以超文本标记语言解析文件,然后将其附加到div下所需的元素。这一切都可以更改,以适应您的需求,从附加元素到您正在使用的链接。我希望这有帮助,如果出现更新、更快的方法而不使用jQuery或W3.js.

更新:这将抛出一个错误,说明本地导入已被CORS策略阻止。由于深网的属性,可能需要访问深网才能使用它。(意味着没有实际用途)

这对我有帮助。为了将HTML代码块从b.html添加到a.html,这应该进入a.htmlhead标签:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

然后在body标签中,用唯一的id和javascript块制作一个容器,将b.html加载到容器中,如下所示:

<div id="b-placeholder">


</div>


<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>

w3.js包括这样的作品:

<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>

为了正确的描述,看看这个:https://www.w3schools.com/howto/howto_html_include.asp

您可以使用超文本标记语言导入的多边形填充(https://www.html5rocks.com/en/tutorials/webcomponents/imports/),或者简化的解决方案 https://github.com/dsheiko/html-import

例如,在您导入超文本标记语言块的页面上,如下所示:

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

区块可能有自己的导入:

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

导入器用加载的超文本标记语言替换指令,非常类似于SSI

这些指令将在您加载这个小JavaScript后立即自动提供:

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

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

我知道这是一个非常古老的帖子,所以当时有些方法是不可用的。 但这是我非常简单的看法(基于Lolo的回答)。

它依赖于HTML5 data-*属性,因此非常通用,因为它使用jQuery的for-each函数来获取每个匹配“load-html”的. class,并使用其各自的“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>

使用es6反引号":模板文字

let nick = "Castor", name = "Moon", nuts = 1


more.innerHTML = `


<h1>Hello ${nick} ${name}!</h1>


You collected ${nuts} nuts so far!


<hr>


Double it and get ${nuts + nuts} nuts!!


` 
<div id="more"></div>

This way we can include html without encoding quotes, include variables from the DOM, and so on.

It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:

let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);

https://caniuse.com/#feat=template-literals

这是我使用Fetch API和async函数的方法

<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>

另一种使用Promise的Fetch API的方法

<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>

要使解决方案工作,您需要包含文件csi.min.js,您可以找到这里

根据GitHub上显示的示例,要使用此库,您必须将文件csi.js包含在页面标头中,然后您需要在容器元素上添加数据包含属性并将其值设置为要包含的文件。

隐藏拷贝代码

<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>

…希望有帮助。

你尝试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在超文本标记语言DOM中)

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

问候

这是我的内联解决方案:

(() => {
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();
});
});
});
})();
<p>FOO</p>


<include src="a.html">Loading...</include>


<p>BAR</p>


<include src="b.html">Loading...</include>


<p>TEE</p>

我还有一个解决办法

在javascript中使用Ajax

这是Github仓库中解释的代码 https://github.com/dupinder/staticHTML-Include

基本思想是:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='main.js'></script>




</head>
<body>
<header></header>


<footer></footer>
</body>
</html>

main.js

fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});


fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});

Web组件

我创建以下web组件类似于JSF

<ui-include src="b.xhtml"><ui-include>

可以使用它作为页面内的常规html标记(包括片段js代码后)

customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
ui-include { margin: 20px } /* example CSS */
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>


<div>My page data... - in this snippet styles overlaps...</div>


<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>

我强烈建议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),从W3学校找到更多信息。

仅使用超文本标记语言无法将超文本标记语言文件包含在另一个超文本标记语言文件中。但这里有一个非常简单的方法来做到这一点。使用这个JS库你可以轻松做到这一点。只需使用此代码:

<script> include('path/to/file.html', document.currentScript) </script>

使用包含HTML(最小的js-lib:~150行)

通过超文本标记语言加载超文本标记语言部分(纯js)
支持的加载:async/sync,任何深度递归包括

支持的协议:超文本传输协议://, https://, file://
支持的浏览器:IE 9+,FF,Chrome(可能还有其他)

用途:

1.将包含HTML插入超文本标记语言文件的头部(或身体关闭标记之前):

<script src="js/includeHTML.js"></script>

2.任何地方使用包含HTML作为超文本标记语言:

<div data-src="header.html"></div>

这里有几种类型的答案,但我从未在这里找到最古老的工具:

“其他的答案对我都不管用。”

<html>
<head>
<title>pagetitle</title>
</head>


<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
<frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">
</frameset>


</html>

w3.js非常酷。

https://www.w3schools.com/lib/w3.js

我们是专注的

w3-包括-html

但考虑下面的情况

- 🧾 popup.html
- 🧾 popup.js
- 🧾 include.js
- 📂 partials
- 📂 head
- 🧾 bootstrap-css.html
- 🧾 fontawesome-css.html
- 🧾 all-css.html
- 🧾 hello-world.html
<!-- popup.html -->
<head>
<script defer type="module" src="popup.js"></script>
<meta data-include-html="partials/head/all-css.html">
</head>


<body>
<div data-include-html="partials/hello-world.html"></div>
</body>
<!-- bootstrap-css.html -->
<link href="https://.../bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />


<!-- fontawesome-css.html -->
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
<!-- all-css.html -->
<meta data-include-html="bootstrap-css.html">
<meta data-include-html="fontawesome-css.html">


<!--
If you want to use w3.js.include, you should change as below


<meta w3-include-html="partials/head/bootstrap-css.html">
<meta w3-include-html="partials/head/fontawesome-css.html">


Of course, you can add the above in the ``popup.html`` directly.


If you don't want to, then consider using my scripts.
-->
<!-- hello-world.html -->
<h2>Hello World</h2>

脚本

// include.js


const INCLUDE_TAG_NAME = `data-include-html`


/**
* @param {Element} node
* @param {Function} cb callback
* */
export async function includeHTML(node, {
cb = undefined
}) {
const nodeArray = node === undefined ?
document.querySelectorAll(`[${INCLUDE_TAG_NAME}]`) :
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`)


if (nodeArray === null) {
return
}


for (const node of nodeArray) {
const filePath = node.getAttribute(`${INCLUDE_TAG_NAME}`)
if (filePath === undefined) {
return
}


await new Promise(resolve => {
fetch(filePath
).then(async response => {
const text = await response.text()
if (!response.ok) {
throw Error(`${response.statusText} (${response.status}) | ${text} `)
}
node.innerHTML = text
const rootPath = filePath.split("/").slice(0, -1)
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`).forEach(elem=>{
const relativePath = elem.getAttribute(`${INCLUDE_TAG_NAME}`) // not support ".."
if(relativePath.startsWith('/')) { // begin with site root.
return
}
elem.setAttribute(`${INCLUDE_TAG_NAME}`, [...rootPath, relativePath].join("/"))
})
node.removeAttribute(`${INCLUDE_TAG_NAME}`)
await includeHTML(node, {cb})
node.replaceWith(...node.childNodes) // https://stackoverflow.com/a/45657273/9935654
resolve()
}
).catch(err => {
node.innerHTML = `${err.message}`
resolve()
})
})
}


if (cb) {
cb()
}
}
// popup.js


import * as include from "include.js"


window.onload = async () => {
await include.includeHTML(undefined, {})
// ...
}

输出

<!-- popup.html -->


<head>


<link href="https://.../bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
</head>


<body>
<h2>Hello World</h2>
</body>

这些解决方案都不适合我的需求。我在寻找更像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_oncerequirerequire_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);

希望有帮助!