我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。

在JSF中,我可以这样做:

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

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

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


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

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的文档插入HTML代码。编写而不是使用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>

研究:

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文件,你可以使用下面的sed命令:

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

或者只是使用以下方便的bash脚本作为Github上的Gist发布,它自动完成所有必要的工作,将b.html转换为b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

感谢Greg Minshall改进的sed命令,它还转义了反斜杠和单引号,这是我最初的sed命令没有考虑到的。

另外,对于支持模板字面量的浏览器,以下方法也适用:

研究:

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

I came to this topic looking for something similar, but a bit different from the problem posed by lolo. I wanted to construct an HTML page holding an alphabetical menu of links to other pages, and each of the other pages might or might not exist, and the order in which they were created might not be alphabetical (nor even numerical). Also, like Tafkadasoh, I did not want to bloat the web page with jQuery. After researching the problem and experimenting for several hours, here is what worked for me, with relevant remarks added:

<!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;
}

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


阿塔里人的回答(第一个!)太有定论了!很好!

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

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

所以它变成了这样:

你的网址:

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是一种服务器级脚本语言。它可以做很多事情,但一个流行的用途是在页面中包含HTML文档,这与SSI非常相似。与SSI一样,这是一种服务器级技术。如果你不确定你的网站上是否有PHP功能,请联系你的主机提供商。

下面是一个简单的PHP脚本,你可以使用它在任何支持PHP的网页上包含HTML片段:

将网站常用元素的HTML保存到单独的文件中。例如,导航部分可以保存为navigation.html或navigation.php。 使用下面的PHP代码将该HTML包含在每个页面中。

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


通过Html5rocks教程检查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());}不提示任何内容,而不是提示包含的内容。

我写下面的代码,在我的解决方案中,你可以访问包含在$(文档)的内容。现成的函数:

(关键是同步加载所包含的内容)。

你可以:

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

Jquery包含在github插件


使用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,他们通常会提供一些模板引擎。 假设您使用了bottle,默认的模板引擎是SimpleTemplate engine。 下面是纯html文件

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

你可以包括页脚。TPL在你的主文件中,比如:

$ cat dashboard.tpl
%include footer

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


目前还没有针对该任务的直接HTML解决方案。即使是HTML导入(这是永久的草案)也不会做这件事,因为Import != Include和一些JS魔法无论如何都是需要的。 我最近写了一个VanillaJS脚本,它只是为了将HTML包含到HTML中,没有任何复杂性。

只要放在你的。html中

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

它是开源的,可能会给你一个想法(我希望)


这是一篇很棒的文章,你可以实现公共库,只需使用下面的代码在一行中导入任何HTML文件。

<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.html和views/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);

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

无论如何,我开始使用这个是为了使它,所以如果我更新一个描述在许多HTML文件中,我只需要更新一个文件来做它(.js文件),而不是每一个包含文本的HTML文件。

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

谢谢你的问题。


你可以用JavaScript的jQuery库来实现这一点,就像这样:

HTML:

<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加载内容,谷歌将无法对其进行索引,因此对于SEO而言,这并不是一个好方法。


基于https://stackoverflow.com/a/31837264/4360308的回答 我用Nodejs (+ express + cheerio)实现了这个功能,如下所示:

HTML (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中

Replace ->替换div

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


html5rocks.com has a very good tutorial on this stuff, and this might be a little late, but I myself didn't know this existed. w3schools also has a way to do this using their new library called w3.js. The thing is, this requires the use of a web server and and HTTPRequest object. You can't actually load these locally and test them on your machine. What you can do though, is use polyfills provided on the html5rocks link at the top, or follow their tutorial. With a little JS magic, you can do something like this:

 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);
 }

This will make the link (Can change to be the wanted link element if already set), set the import (unless you already have it), and then append it. It will then from there take that and parse the file in HTML, and then append it to the desired element under a div. This can all be changed to fit your needs from the appending element to the link you are using. I hope this helped, it may irrelevant now if newer, faster ways have come out without using libraries and frameworks such as jQuery or W3.js.

UPDATE:这将抛出一个错误,表示本地导入已被CORS策略阻塞。可能需要访问深层网络才能使用它,因为深层网络的特性。(意思是没有实际用途)


这对我很有帮助。为了将一个html代码块从b.html添加到a.html,这应该放在a.html的head标签中:

<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中include是这样工作的:

<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


您可以使用HTML Imports的填充(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)或简化的解决方案 https://github.com/dsheiko/html-import

例如,在你导入HTML块的页面上:

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

该块可以有自己的导入:

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

导入器用加载的HTML替换指令,就像SSI一样

这些指令将在你加载这个小JavaScript时自动提供:

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

它将在DOM准备就绪时自动处理导入。此外,它还公开了一个API,您可以使用该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 更多。innerHTML = ' <h1>Hello ${nick} ${name}!< / h1 > 到目前为止你收集了${nuts} nuts ! <人力资源> 加倍就能得到${坚果+坚果}坚果!! ` < div id = "更多" > < / div >

通过这种方式,我们可以在不编码引号的情况下包含html,包括来自DOM的变量,等等。

它是一个强大的模板引擎,我们可以使用单独的js文件和使用事件来加载内容,甚至将所有内容分成块并按需调用:

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>

另一种方法是使用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>

要让解决方案工作,您需要包括文件csi.min.js,您可以在这里找到它。

根据GitHub上显示的例子,要使用这个库,你必须在你的页头中包含文件csi.js,然后你需要在容器元素上添加data-include属性,将其值设置为你想要包含的文件。

隐藏复制代码

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

... 希望能有所帮助。


你试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在HTML DOM中)

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

问候


这是我的内联解决方案:

(() => { const includes = document.getElementsByTagName('include'); [] .forEach。调用(包含I => { let filePath = i.getAttribute('src'); fetch (filePath)。然后(file => { file.text()。然后(content => { i.insertAdjacentHTML(“afterend”、内容); i.remove (); }); }); }); }) (); FOO < p > < / p > <包括src = " a.html " >加载…< /包括> 酒吧< p > < / p > <包括src = " b.html " >加载…< /包括> < p > t < / p >


我还有一个解

在javascript中使用Ajax

以下是Github repo中的解释代码 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组件

我创建了以下类似JSF的web组件

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

你可以在你的页面中使用它作为常规的html标签(在包括snippet 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),更多信息可以从W3Schools中获取。


仅使用HTML是不可能将HTML文件包含在另一个HTML文件中。这里有一个很简单的方法。使用这个JS库你可以很容易地做到这一点。只需使用以下代码:

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

使用includeHTML(最小js-lib:约150行)

通过HTML标签加载HTML部件(纯js) 支持加载:异步/同步,任何深度递归包括

支持的协议:http://, https://,文件:/// 支持的浏览器:IE 9+, FF, Chrome(也可能是其他)

用法:

1.在HTML文件中插入includeHTML到头部部分(或在正文结束标记之前):

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

2.在任何地方使用includeHTML作为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>

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

希望能有所帮助!