807

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?

9

44 Answers 44

824

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.

21
  • 8
    What is the difference of doing just this `<script>$("#includedContent").load("b.html");</script> ? Apr 11, 2015 at 4:52
  • 20
    @RodrigoRuiz $(function(){}) will only execute after the document finishes loading.
    – ProfK
    May 10, 2015 at 16:20
  • 10
    If the included HTML file has CSS attached to it, it might mess up your page style. Oct 7, 2015 at 14:19
  • 6
    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?. Oct 8, 2015 at 19:01
  • 90
    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.
    – Basj
    Dec 4, 2016 at 12:02
224

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.

4
  • 1
    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
    Apr 8, 2016 at 9:45
  • 1
    @chris You can use GET params e.g. $("#postdiv").load('posts.php?name=Test&age=25');
    – Nam G VU
    May 6, 2016 at 8:08
  • 2
    not working on chrome with local files "Cross origin requests are only supported for protocol schemes: htt" Sep 10, 2017 at 15:41
  • 2
    @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/…
    – mwiegboldt
    Sep 10, 2017 at 20:53
196

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>

`);
15
  • 4
    @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...
    – Tafkadasoh
    Apr 23, 2014 at 7:59
  • 2
    It's trivial to do Ajax with plain JS and no jQuery. For starters, see stackoverflow.com/questions/8567114/….
    – EML
    Sep 2, 2014 at 9:46
  • 4
    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.
    – jbyrd
    Dec 8, 2016 at 19:18
  • 1
    @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
    Nov 2, 2017 at 18:22
  • 1
    @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. :-)
    – Tafkadasoh
    Jan 15, 2018 at 6:40
98

Checkout HTML5 imports via Html5rocks tutorial and at polymer-project

For example:

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>
6
  • 36
    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.
    – waldyrious
    Oct 25, 2014 at 18:18
  • 1
    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. Aug 27, 2015 at 11:29
  • 3
    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.
    – Maxim
    Jan 3, 2017 at 19:51
  • 20
    Update late 2018: HTML imports are apparently being deprecated for some reason Nov 8, 2018 at 1:55
  • 5
    HTML Imports are deprecated and was removed from Chrome in February 2020.
    – Paulo Ney
    Aug 26, 2020 at 0:42
85

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.

10
  • 4
    Will this evaluate JavaScript if include.html has it embedded?
    – Seth
    Feb 18, 2014 at 21:14
  • 1
    @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
    – xandout
    Oct 16, 2014 at 2:29
  • 2
    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!! :-)
    – kpollock
    Jul 30, 2016 at 14:27
  • 1
    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. Apr 4, 2018 at 18:50
  • 1
    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
    – yeppe
    Dec 20, 2018 at 7:26
72

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

6
  • 10
    it does not seem to apply css styles from the parent page for instance.
    – Randy
    Oct 24, 2014 at 21:48
  • 6
    @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.
    – bjb568
    Oct 24, 2014 at 23:24
  • Answered my needs for the answer to this question - how to include an html file in another html file...
    – Grimxn
    Nov 10, 2015 at 22:09
  • 24
    The seamless attribute has been removed from the HTML draft it came from. Don't use it.
    – Mitja
    Mar 28, 2017 at 15:25
  • 1
    Fantastic, I can include a whole html document thas has interactive 3D plots with this. Thank you!
    – pglpm
    Jun 24, 2020 at 16:04
50

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" -->
6
  • 26
    You need to config your server for using SSI
    – lolo
    Jun 24, 2013 at 6:15
  • 7
    Here is a reference for configuring the SSI for your server: httpd.apache.org/docs/2.4/howto/ssi.html#configuring Jan 19, 2015 at 3:41
  • 1
    Might be worth trying <!--#include file="a.html" --> as well
    – james
    Sep 3, 2015 at 12:34
  • SSI Inclusion make Web-Server a tad slower (so should be avoided until absolute necessity).
    – Amit Verma
    Oct 18, 2015 at 14:19
  • 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
    – bendecko
    Apr 28, 2021 at 8:47
37

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]-->
4
  • 12
    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
    – waldyrious
    Oct 25, 2014 at 18:24
  • 3
    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?) Aug 26, 2018 at 20:30
  • 3
    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.
    – waldyrious
    Sep 16, 2018 at 20:04
  • to not show scrollbars, should style this to be inline-block, see anycodings.com/1questions/2247104/… Oct 14, 2022 at 14:34
30

Here is my inline solution:

(() => {
    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>

4
  • It works but script will not work for this included document. Nov 15, 2020 at 16:21
  • @MuhammadSaquibShaikh do you mean the snippet? it sure won't work, because jsfiddle don't have a multiple file infrastructure Nov 15, 2020 at 18:00
  • Im loading another html file with (having script tag for js file) but js code shows null for selecting DOM element Nov 16, 2020 at 15:24
  • Simple Easy script. Works perfectly to simply include HTML files. Nice work! @MuhammadSaquibShaikh It's not really meant for running script tags though.
    – Mqx
    Mar 31, 2023 at 8:17
27

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

4
  • 4
    Works like a charm and it's the cleanest solution. This should be the accepted answer.
    – vbocan
    Aug 10, 2016 at 5:11
  • Agree. Just one note: do not try to do a self-closing object tag. The text after it will get erased. Nov 14, 2016 at 7:53
  • It seems to create a new "#document" which automatically contains new, nested <html> and <body> tags. This did not work for my purpose; my .html file contains <script src="..." type="text/javascript"> tags; but the JS got new reference errors.
    – IAM_AL_X
    Nov 28, 2018 at 4:49
  • should style this to be inline-block, see anycodings.com/1questions/2247104/… Oct 14, 2022 at 14:33
18

In w3.js include works like this:

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

For proper description look into this: https://www.w3schools.com/howto/howto_html_include.asp

2
  • If you want to know when the document has been loaded, you can put this at the end of the document: <img src="thisimagedoesnotexist.dmy" onerror='initDocument()' style='display:none;'> Clever trick, eh? Oct 2, 2018 at 6:51
  • The w3-include-HTML methode is not really efficient. The script which they have wrote as an example is quite awkward and complicated. This is much more efficient.
    – Mqx
    Mar 31, 2023 at 8:20
17

As an alternative, if you have access to the .htaccess file on your server, you can add a simple directive that will allow php to be interpreted on files ending in .html extension.

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

Now you can use a simple php script to include other files such as:

<?php include('b.html'); ?>
6
  • 30
    Yeah that's is a very bad advice. Html files are static, and are served by apache very fast. If you add all html files to the php parser just to inlcude files, you will have a lot of performance problems on your servers. The javascript way (jQuery or plain JS) are not very good solutions, but they still are way more efficient and less dangerous than this one.
    – Gfra54
    May 23, 2014 at 8:18
  • @Gfra54 Do you mean that we will have performance issues if we use Apache only for this, and we don't do any php work for the site? Or will it slow down if I use php and this thing together? May 23, 2014 at 15:12
  • 1
    Caution: Adding these lines to .htaccess may cause html pages to try to download as files rather than view in browser. Test first. Disclaimer: That just now happened to me when I tried the above solution. My .htaccess was empty except for above two lines. Caution advised. Try lolo's jQuery solution (below) instead.
    – cssyphus
    Dec 29, 2015 at 19:38
  • man I was complicating myself even though I have done it before. Thanks for the reminder. For the purpose I need it doesn't really affect performance so I'm cool.
    – Gman
    Jun 16, 2016 at 7:08
  • Ha this performance-crushing answer is an awesome example of out-of-the-box thinking. I would never suggest it, but maybe a lifesaver when you need a quick bit of php sledgehammer. :-)
    – moodboom
    Jan 7, 2017 at 15:44
14

This is what helped me. For adding a block of html code from b.html to a.html, this should go into the head tag of a.html:

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

Then in the body tag, a container is made with an unique id and a javascript block to load the b.html into the container, as follows:

<div id="b-placeholder">

</div>

<script>
$(function(){
  $("#b-placeholder").load("b.html");
});
</script>
3
  • 6
    How this answer is different from the accepted answer of this question? Jan 16, 2018 at 12:26
  • 3
    @MohammadUsman Here the container and javascript code lie in the body tag while the accepted answer places them in the head tag and leaving the container in the body tag only.
    – Ramtin
    Jan 16, 2018 at 15:57
  • This doesn't worth a new answer ... it's a comment Nov 28, 2019 at 18:18
11

I know this is a very old post, so some methods were not available back then. But here is my very simple take on it (based on Lolo's answer).

It relies on the HTML5 data-* attributes and therefore is very generic in that is uses jQuery's for-each function to get every .class matching "load-html" and uses its respective 'data-source' attribute to load the content:

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

You can use a polyfill of HTML Imports (https://www.html5rocks.com/en/tutorials/webcomponents/imports/), or that simplified solution https://github.com/dsheiko/html-import

For example, on the page you import HTML block like that:

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

The block may have imports of its own:

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

The importer replaces the directive with the loaded HTML pretty much like SSI

These directives will be served automatically as soon as you load this small JavaScript:

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

It will process the imports when DOM is ready automatically. Besides, it exposes an API that you can use to run manually, to get logs and so on. Enjoy :)

3
8

Most of the solutions works but they have issue with jquery:

The issue is following code $(document).ready(function () { alert($("#includedContent").text()); } alerts nothing instead of alerting included content.

I write the below code, in my solution you can access to included content in $(document).ready function:

(The key is loading included content synchronously).

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>

jquery include plugin on github

3
  • When using this and then viewing the page source from a browser you only see the script. Doesn't this affect a search engines ability to parse your site, ultimately destroying any SEO efforts? Oct 7, 2014 at 14:56
  • Yes, this method destroying any SEO :) Oct 18, 2014 at 10:42
  • Then again, every JavaScript-based method does so.
    – wizzwizz4
    Nov 2, 2017 at 18:28
7

Here's my approach using Fetch API and async function

<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>
1
  • Please explain your code, by adding comments. Apr 12, 2022 at 14:47
7

Another approach using Fetch API with 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>
7

Use includeHTML (smallest js-lib: ~150 lines)

Loading HTML parts via HTML tag (pure js)
Supported load: async/sync, any deep recursive includes

Supported protocols: http://, https://, file:///
Supported browsers: IE 9+, FF, Chrome (and may be other)

USAGE:

1.Insert includeHTML into head section (or before body close tag) in HTML file:

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

2.Anywhere use includeHTML as HTML tag:

<div data-src="header.html"></div>
2
  • @Williams, thanks a lot to you for feedback my work!
    – xmoonlight
    Oct 12, 2021 at 9:24
  • You can’t really claim it supports the file:// protocol when the support amounts to an alert() telling you to turn off Chrome web security (CORS check).
    – Shaw
    Sep 2, 2023 at 19:08
7

Web Components

I create following web-component similar to JSF

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

You can use it as regular html tag inside your pages (after including snippet js code)

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>

(stackoverflow snippet will work better (load full pages, not only message) when you first go here and push button to give your computer temporary acces to cors-anywhere)

2
  • How do we do it with no JavaScript Aug 14, 2020 at 23:10
  • 1
    it probably makes sense to use display: contents on that element too, to make the <ui-include> layout disappear. I think that's the expected behavior.
    – nachoab
    Sep 10, 2020 at 21:19
6

To insert contents of the named file:

<!--#include virtual="filename.htm"-->
2
  • 1
    using angle brackets for [ ]:[ !--#include virtual="include_omega.htm"-- ]
    – St.Eve
    Aug 18, 2013 at 5:38
  • This needs a server! It does not work on local files.
    – Paulo Ney
    Aug 26, 2020 at 0:58
6

Did you try a iFrame injection?

It injects the iFrame in the document and deletes itself (it is supposed to be then in the HTML DOM)

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

Regards

1
  • this does not work in file:// I want to develop locally without a server. This only works with a server and then at that point just use SSI. Can you get this to work without a server? Jul 16, 2022 at 9:31
5

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: This will throw an error saying that the local import has been blocked by CORS policy. Might need access to the deep web to be able to use this because of the properties of the deep web. (Meaning no practical use)

5

None of these solutions suit my needs. I was looking for something more PHP-like. This solution is quite easy and efficient, in my opinion.

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

Simple tweaks can be made to create include_once, require, and require_once, which may all be useful depending on what you're doing. Here's a brief example of what that might look like.

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

Hope it helps!

1
  • I like that you don't need to parse the whole DOM with this.
    – arkan
    Nov 20, 2023 at 16:30
4

The Athari´s answer (the first!) was too much conclusive! Very Good!

But if you would like to pass the name of the page to be included as URL parameter, this post has a very nice solution to be used combined with:

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

So it becomes something like this:

Your URL:

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

The a.html code now becomes:

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

It worked very well for me! I hope have helped :)

1
  • Security problem, bacause you can send somebody this link: www.yoursite.com/a.html?p=htttp://www.linktovir.us/here.html
    – Mr. Hugo
    Oct 15, 2019 at 18:43
3

There is no direct HTML solution for the task for now. Even HTML Imports (which is permanently in draft) will not do the thing, because Import != Include and some JS magic will be required anyway.
I recently wrote a VanillaJS script that is just for inclusion HTML into HTML, without any complications.

Just place in your a.html

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

It is open-source and may give an idea (I hope)

0
3

You can do that with JavaScript's library jQuery like this:

HTML:

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

JS:

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

Please note that banner.html should be located under the same domain your other pages are in otherwise your webpages will refuse the banner.html file due to Cross-Origin Resource Sharing policies.

Also, please note that if you load your content with JavaScript, Google will not be able to index it so it's not exactly a good method for SEO reasons.

2

Here is a great article, You can implement common library and just use below code to import any HTML files in one line.

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

You can also try Google Polymer

3
  • 8
    "just use below code to import any HTML files in one line" is pretty disingenuous. You have to then write some JS to make use of any content you imported, so it ends up being way more than "one line".
    – skybondsor
    Apr 15, 2017 at 13:42
  • HTML Imports are deprecated and was removed from Chrome in February 2020.
    – Paulo Ney
    Aug 26, 2020 at 1:01
  • @PauloNey This isn't import, it's link.
    – johny why
    Nov 27, 2022 at 20:47
2

To get Solution working you need to include the file csi.min.js, which you can locate here.

As per the example shown on GitHub, to use this library you must include the file csi.js in your page header, then you need to add the data-include attribute with its value set to the file you want to include, on the container element.

Hide Copy Code

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

... hope it helps.

1
  • this only works if you run it on a server. I want to do dev locally without a server. Jul 16, 2022 at 9:33
2

There are several types of answers here, but I never found the oldest tool in the use here:

"And all the other answers didn't work for me."

<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>
2
  • w3schools.com/TAgs/tag_frame.asp - HTML <frame> tag is not supported in HTML5 :(
    – Rublacava
    Jul 5, 2022 at 22:34
  • If I recall correctly frames are nowadays blocked quite often since in the past they were exploited by advertisers and mostly for spreading malicious content. Sep 24, 2022 at 21:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.