ChatGPT解决这个技术问题 Extra ChatGPT

Include another HTML file in a HTML file

I have 2 HTML files, suppose a.html and b.html. In a.html I want to include b.html.

In JSF I can do it like that:

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

It means that inside a.xhtml file, I can include b.xhtml.

How can we do it in *.html file?


S
SharpC

In my opinion the best solution uses 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>

This method is a simple and clean solution to my problem.

The jQuery .load() documentation is here.


What is the difference of doing just this ` ?
@RodrigoRuiz $(function(){}) will only execute after the document finishes loading.
If the included HTML file has CSS attached to it, it might mess up your page style.
I am exactly like you have mentioned. I am using bootstrap and have css overwrites for B.html. When I use B.html in A.html so that it would end up as A.html's header, I can see that the css has lost its priority and has a different layout. Any solutions to this?.
This does require a server. When using it on a local file: XMLHttpRequest cannot load file:///.../b.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
T
Trenton McKinney

Expanding lolo's answer, here is a little more automation if you have to include a lot of files. Use this JS code:

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

And then to include something in the html:

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

Which would include the file views/header.html and views/footer.html.


Very useful. Is there a way to pass an argument through another data parameter, like data-argument and retrieve it in the included file?
@chris You can use GET params e.g. $("#postdiv").load('posts.php?name=Test&age=25');
not working on chrome with local files "Cross origin requests are only supported for protocol schemes: htt"
@ArtemBernatskyi Does it help, when you run a local server instead? Here is an easy tutorial: developer.mozilla.org/en-US/docs/Learn/Common_questions/…
C
Chris Magnuson

My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using 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>\
\
');

The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.

In order to get the properly escaped JavaScript file without much work, you can use the following sed command:

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

Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html to b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.

Alternatively for browsers that support template literals the following also works:

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>

`);

@TrevorHickey Yes, you're right, that's the drawback of my solution, and that isn't very elegant. However, as you can insert an '\' with a simple regex at the end of each line, this works for me best. Hmm... maybe I should add to my answer how to do the insertion via regex...
It's trivial to do Ajax with plain JS and no jQuery. For starters, see stackoverflow.com/questions/8567114/….
Oh sheesh, that's ugly - no thanks. I'd rather write my html as html. I don't care if I can use sed on the command line - I don't want to have to rely on that every time I change the contents of the template.
@Goodra It should work on any HTML without ' marks in it. If you just do a find / replace to replace ` with \` THEN find / replace to replace ' with \' and new-lines with ``new-lines it will work fine.
@wizzwizz4: Thanks to Greg, the sed command now also escapes single quotes and backslashes. Furthermore, I've added a bash script that does all the work for you. :-)
S
Supersharp

Checkout HTML5 imports via Html5rocks tutorial and at polymer-project

For example:

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

HTML imports are not meant to actually include the content in the page directly. The code in this answer only makes stuff.html available as a template within the parent page, but you'd have to use scripting to create clones of its DOM in the parent page so that they're visible to the user.
The instructions at html5rocks.com for inserting the contents of one HTML page into another don't seem to work in a lot of browsers out there, yet. I tried it in Opera 12.16 and Superbird Version 32.0.1700.7 (233448) without effect (on Xubuntu 15.04). I hear it doesn't work in Firefox (due to a bug that hopefully has been fixed) or a lot of versions of Chrome, though. So, while it looks like it may be an ideal solution in the future, it's not a cross-browser solution.
Firefox will not support it. To enable it try to set "dom.webcomponents.enabled". It will work only in Chrome and Opera, Android with updatable web view (startng 4.4.3). Apple browsers do not support it. It looks like a nice idea for web-components but not wide implemented yet.
Update late 2018: HTML imports are apparently being deprecated for some reason
HTML Imports are deprecated and was removed from Chrome in February 2020.
M
Michael Marr

Shameless plug of a library that I wrote the solve this.

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

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

The above will take the contents of /path/to/include.html and replace the div with it.


Will this evaluate JavaScript if include.html has it embedded?
@Seth it doesn't seem to. I am going to play around with the src and see if I can make it do that. Thanks to michael-marr
Brilliant!!!! Yours seems the only solution that REPLACES the div tag used as a token for where to insert. I'm gonna study the source carefully later!! :-)
thanks this works, it includes the HTML/CSS but not the Javascript from source files. You just have to include it again wherever you use the <div data-include="/path/to/include.html"></div>. This tool makes it easier to make a simple no-plugin multipage mockup in a clean way.
can I use this lib in any application? I mean how can credit the author ? W3School has similar solution, only difference it that your code caters to recursive call on window load as well ....w3schools.com/howto/tryit.asp?filename=tryhow_html_include_1
b
bjb568

No need for scripts. No need to do any fancy stuff server-side (tho that would probably be a better option)

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

Since old browsers don't support seamless, you should add some css to fix it:

iframe[seamless] {
    border: none;
}

Keep in mind that for browsers that don't support seamless, if you click a link in the iframe it will make the frame go to that url, not the whole window. A way to get around that is to have all links have target="_parent", tho the browser support is "good enough".


it does not seem to apply css styles from the parent page for instance.
@Randy So? This could be counted as a plus (especially for user-generated content and the like). You can easily include the css files again anyway without making another request because of caching anyway.
Answered my needs for the answer to this question - how to include an html file in another html file...
The seamless attribute has been removed from the HTML draft it came from. Don't use it.
awesome this works work for MarkDown as well. Tested on Typora.
b
bendecko

A simple server side include directive to include another file found in the same folder looks like this:

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

Also you can try:

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

You need to config your server for using SSI
Here is a reference for configuring the SSI for your server: httpd.apache.org/docs/2.4/howto/ssi.html#configuring
Might be worth trying <!--#include file="a.html" --> as well
SSI Inclusion make Web-Server a tad slower (so should be avoided until absolute necessity).
For IIS this is a nice solution also. I had to add ` <add name="SSINC-html" path=".html" verb="" modules="ServerSideIncludeModule" resourceType="File" />` to my web.config file in the <handlers> section
b
bjb568

A very old solution I did met my needs back then, but here's how to do it standards-compliant code:

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

It appears that <object>, <embed> and <iframe> all work for this, but in all three cases they create separate documents with their own styling and scripting contexts (iframe particularly includes ugly borders and scrollbars), and for instance any links by default open within them rather than on the parent page (although this can be overridden with target="_parent"). From all of these, iframe is the only one that has some hope of becoming more integrated through the HTML5 seamless attribute (mentioned by bjb568), but it's not yet well supported: caniuse.com/#feat=iframe-seamless
iframe-seamless has been dropped from the HTML standard: github.com/whatwg/html/issues/331. So @waldyrious comment is not longer correct (mind to update it your comment?)
Thanks for the heads-up, @TomášPospíšek. I can't edit my comment anymore, but hopefully your response provides the necessary caveat to readers. To be clear, the last sentence (about the seamless attribute) is the only outdated part -- the rest still applies.
C
CoolDude

Following works if html content from some file needs to be included: For instance, the following line will include the contents of piece_to_include.html at the location where the OBJECT definition occurs.

...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...

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


Works like a charm and it's the cleanest solution. This should be the accepted answer.
Agree. Just one note: do not try to do a self-closing object tag. The text after it will get erased.
It seems to create a new "#document" which automatically contains new, nested and tags. This did not work for my purpose; my .html file contains