By lolo


2012-01-24 14:51:16 8 Comments

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?

30 comments

@Dupinder Singh 2020-05-14 15:32:02

I have one more solution to do this

Using Ajax in javascript

here is the explained code in Github repo https://github.com/dupinder/staticHTML-Include

basic idea is:

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

@Mustafa Burak Kalkan 2019-12-09 13:12:51

Here is my in-place 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>

@Arian saputra 2019-12-12 00:07:10

woow, it's more simple

@Remling 2020-03-07 17:52:32

Really nice and simple solution, thanks ^^

@Tafkadasoh 2013-03-06 14:40:12

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>

`);

@Tafkadasoh 2014-04-23 07:59:26

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

@EML 2014-09-02 09:46:24

It's trivial to do Ajax with plain JS and no jQuery. For starters, see stackoverflow.com/questions/8567114/….

@Yvon Huynh 2016-09-18 07:48:20

This should be the chosen solution,using Jquery to do something as simple as this is not optimal.

@jbyrd 2016-12-08 19:18:34

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.

@VortexYT 2017-10-25 20:11:36

Does this work on any HTMl such as ones with <script></script> in?

@wizzwizz4 2017-11-02 18:22:56

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

@Tafkadasoh 2018-01-15 06:40:31

@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. :-)

@inetphantom 2018-09-24 15:59:40

You can use backticks ` - then you are able to insert expressions like ${var} - you then only need to escape \` and \$

@Momoro 2020-04-10 06:26:52

Oooooooohhh! Awesome! Now I can include my navigation bar without cluttering every page.. heheh!

@Alban Lusitanae 2019-10-11 16:07:23

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

@Hamza Ali 2019-08-06 06:50:12

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.

@Kaj Risberg 2017-04-12 09:32:40

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

@Kaj Risberg 2018-10-02 06:51:15

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?

@deepcell 2019-02-04 06:20:33

is not working with google chrome.

@pinei 2019-03-25 03:37:01

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>

@barro32 2019-01-08 13:17:55

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>

@NVRM 2018-11-21 21:23:09

Using ES6 backticks ``: template literals!

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

@Ben Mc 2018-03-27 01:33:16

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>

@mhanisch 2015-08-05 15:52:48

Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files:

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

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

@chris 2016-04-08 09:45:59

Very useful. Is there a way to pass an argument through another data parameter, like data-argument and retrieve it in the included file?

@Nam G VU 2016-05-06 08:08:44

@chris You can use GET params e.g. $("#postdiv").load('posts.php?name=Test&age=25');

@jbyrd 2016-12-08 19:32:52

Small suggestion - you don't need the class="include" - just make your jQuery selector var includes = $('[data-include]');

@Artem Bernatskyi 2017-09-10 15:41:07

not working on chrome with local files "Cross origin requests are only supported for protocol schemes: htt"

@mhanisch 2017-09-10 20:53:01

@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/…

@Dmitry Sheiko 2017-08-03 12:23:13

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

@Andrew Truckle 2018-10-27 21:07:42

Where should the script line go in the html File?

@Dmitry Sheiko 2018-10-29 08:51:18

Anywhere within BODY. Can be placed recursively in the content of the included files

@Bhikkhu Subhuti 2020-02-29 06:21:16

Did you test this?

@Dmitry Sheiko 2020-03-06 12:49:14

Surely I did. I have been actually using it for years. Why asking? Any problems?

@Ramtin 2017-02-19 22:11:21

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>

@Mohammad Usman 2018-01-16 12:26:12

How this answer is different from the accepted answer of this question?

@Ramtin 2018-01-16 15:57:57

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

@Kennet Celeste 2019-11-28 18:18:25

This doesn't worth a new answer ... it's a comment

@SubLock69 2017-02-17 02:48:23

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)

@lolo 2012-01-25 13:17:19

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.

@Rodrigo Ruiz 2015-04-11 04:52:43

What is the difference of doing just this `<script>$("#includedContent").load("b.html");</script> ?

@ProfK 2015-05-10 16:20:56

@RodrigoRuiz $(function(){}) will only execute after the document finishes loading.

@cregox 2015-05-12 20:46:48

Awesome! But how about using $("div").appendTo('body').load("b.html"); and dropping the whole div includedContent instead? Makes it much easier to include many other files! :)

@Kirby 2015-09-08 22:09:38

@Cawas, wouldn't that stick b.html into every div?

@cregox 2015-09-08 22:18:30

Yes it would @Kirby. I meant $("#includedContent"), which would make more sense in this context. Thanks for the tip! ;)

@Omar Jaafor 2015-10-07 14:19:17

If the included HTML file has CSS attached to it, it might mess up your page style.

@Pavan Dittakavi 2015-10-08 19:01:50

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

@Cobra47 2016-04-12 20:18:58

I've been searching for an answer for like an hour. This is the best answer anyone could find for such question!

@Jaycee Evangelista 2016-09-01 06:15:23

Does the file I will include needs to have the <html>...</html> and other parts? Or can I just have the line of code itself? for example, <p>display</p>

@parsecer 2016-09-13 16:07:55

@Jaycee Evangelista Try both. Not sure what happens if you include <html><body... into an html file which already has all those tags, but I just use <p>...</p> -type included files.

@Basj 2016-12-04 12:02:34

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.

@MeRuud 2016-12-06 15:11:29

@Basj you can get around that, for now, by using Firefox instead. I think there is also a chrome add-in available to get around this. More info here: stackoverflow.com/questions/20041656/…

@java-addict301 2017-10-26 15:19:47

@JayceeEvangelista You probably should use a valid complete HTML file if the extension is .html or .htm. You can however, use this method to only load certain elements using $("#result").load( "ajax/test.html #container" ); (in this case, only the container element would be inserted. See api.jquery.com/load/#loading-page-fragments for details).

@AndroidDev 2018-09-04 07:53:29

If you need to debug your code in Chrome, anything you load dynamically will not show up in DevTools.

@inetphantom 2018-09-22 20:56:19

@jpaugh 2018-09-24 15:00:51

@inetphantom Thanks! I'd forgotten about there being two of them! (I'm so happy they removed it!)

@desmond13 2019-05-15 18:56:33

I do not understand what I should put into my jQuery.js file (this file is empty for me by the way)

@Guseyn Ismayylov 2019-11-20 11:25:25

There is a quite nice solution: e-html element from EHTML library, it allows you to use sort of module system in HTML. github.com/Guseyn/EHTML

@Bhikkhu Subhuti 2020-02-29 08:47:08

You can include files if fileuristrict is set to false in firefox. Chrome has an equivalent

@user1587439 2014-03-03 08:41:56

Checkout HTML5 imports via Html5rocks tutorial and at polymer-project

For example:

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

@waldyrious 2014-10-25 18:18:56

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.

@Brōtsyorfuzthrāx 2015-08-27 11:29:06

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.

@sphakka 2016-12-10 15:32:12

Apparently not ready as of end 2016 in FireFox (45.5.1 ESR). JS console says: TypeError: ... .import is undefined. MDN says "This feature is not implemented in any browsers natively at this time." Does anybody know if it is possible to build FF with this feature?

@Maxim 2017-01-03 19:51:03

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.

@V. Rubinetti 2018-11-08 01:55:05

Update late 2018: HTML imports are apparently being deprecated for some reason

@giroxiii 2016-08-03 21:31:33

Based on the answer of https://stackoverflow.com/a/31837264/4360308 I've implemented this functionality with Nodejs (+ express + cheerio) as follows:

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 -> includes the content into the div

replace -> replaces the div

you could easily add more behaviours following the same design

@AndrewL64 2015-09-19 23:13:37

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.

@Brōtsyorfuzthrāx 2015-08-28 01:33:34

Well, if all you're wanting to do is put text from a separate file into your page (tags in the text should work, too), you can do this (your text styles on the main page—test.html—should still work):

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

You can always recreate the HTML tags you want yourself, after all. There's need for server-side scripting just to grab text from another file, unless you want to do something more.

Anyway, what I'm starting to use this for is to make it so if I update a description common among lots of HTML files, I only need to update one file to do it (the .js file) instead of every single HTML file that contains the text.

So, in summary, instead of importing an .html file, a simpler solution is to import a .js file with the content of the .html file in a variable (and write the contents to the screen where you call the script).

Thanks for the question.

@Dhiral Pandya 2015-06-17 17:56:08

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

@skybondsor 2017-04-15 13:42:10

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

@al.scvorets 2015-04-29 15:14:33

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)

@jaseywang 2015-03-18 07:43:52

If you use some framework like django/bootle, they often ship some template engine. Let's say you use bottle, and the default template engine is SimpleTemplate Engine. And below is the pure html file

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

You can include the footer.tpl in you main file, like:

$ cat dashboard.tpl
%include footer

Besides that, you can also pass parameter to your dashborard.tpl.

@Aleksandar Vacić 2013-04-19 16:04:33

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

@waldyrious 2014-10-25 18:24:53

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

@Tomáš Pospíšek 2018-08-26 20:30:05

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

@waldyrious 2018-09-16 20:04:40

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.

@Bear Bear 2014-08-06 19:18:53

using jquery u need import library

i recommend you using php

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

b.html

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

@Amir Saniyan 2014-06-13 15:23:18

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

@hmcclungiii 2014-10-07 14:56:54

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?

@Amir Saniyan 2014-10-18 10:42:32

Yes, this method destroying any SEO :)

@wizzwizz4 2017-11-02 18:28:55

Then again, every JavaScript-based method does so.

@CoolDude 2014-05-20 07:11: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

@vbocan 2016-08-10 05:11:11

Works like a charm and it's the cleanest solution. This should be the accepted answer.

@Sridhar Sarnobat 2016-11-14 07:53:48

Agree. Just one note: do not try to do a self-closing object tag. The text after it will get erased.

@IAM_AL_X 2018-11-28 04:49:35

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.

@Michael Marr 2014-01-13 16:51:27

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.

@Seth 2014-02-18 21:14:44

Will this evaluate JavaScript if include.html has it embedded?

@xandout 2014-10-16 02:29:36

@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

@kpollock 2016-07-30 14:27:14

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!! :-)

@miket 2018-03-22 08:40:41

This is it! Thanks!

@Vincent Tang 2018-04-04 18:50:36

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.

@Vincent Tang 2018-04-04 19:18:26

Also, if you write inline javascript on the file calling the imports, you need to use a setTimeOut(func,4000); and then the calling function func(){ /* do stuff here */}); because Javascript doesn't know when the source html/css are loaded in. As opposed to just using a jquery $(document).ready(function(){})

@Pro Q 2018-07-03 06:16:27

Why is this better? Because it's literally one line of javascript versus how many megabytes of jQuery! And it works for pure HTML. Will be using this for static headers. (Just thought I'd clarify/promo because if you don't click on the link you don't know how small it is.)

@yeppe 2018-12-20 07:26:56

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_inclu‌​de_1

@Udara Pathirage 2013-12-26 12:45:09

PHP is a server level scripting language. It can do many things, but one popular use is to include HTML documents inside your pages, much the same as SSI. Like SSI, this is a server level technology. If you are not sure if you have PHP functionality on your website contact your hosting provider.

Here is a simple PHP script you can use to include a snippet of HTML on any PHP-enabled web page:

Save the HTML for the common elements of your site to separate files. For example, your navigation section might be saved as navigation.html or navigation.php. Use the following PHP code to include that HTML in each page.

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

Use that same code on every page that you want to include the file. Make sure to change the higlighted file name to the name and path to your include file.

@Massa 2013-12-19 17:05:09

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

@JoostS 2019-10-15 18:43:47

Security problem, bacause you can send somebody this link: www.yoursite.com/a.html?p=htttp://www.linktovir.us/here.html

@bjb568 2013-11-27 00:52:02

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

@Randy 2014-10-24 21:48:52

it does not seem to apply css styles from the parent page for instance.

@bjb568 2014-10-24 23:24:02

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

@Grimxn 2015-11-10 22:09:44

Answered my needs for the answer to this question - how to include an html file in another html file...

@DBS 2016-07-15 01:50:42

That's the best answer WITHOUT JQuery or scripts. Nice bjb568 thanks!

@Mitja 2017-03-28 15:25:29

The seamless attribute has been removed from the HTML draft it came from. Don't use it.

@Foad 2019-03-13 22:58:16

awesome this works work for MarkDown as well. Tested on Typora.

Related Questions

Sponsored Content

33 Answered Questions

[SOLVED] Make a div fill the height of the remaining screen space

  • 2008-09-18 05:06:17
  • Vincent McNabb
  • 1016940 View
  • 1909 Score
  • 33 Answer
  • Tags:   html css html-table

52 Answered Questions

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

18 Answered Questions

[SOLVED] How to get the children of the $(this) selector?

41 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

37 Answered Questions

28 Answered Questions

9 Answered Questions

[SOLVED] Why does HTML think “chucknorris” is a color?

25 Answered Questions

[SOLVED] In Node.js, how do I "include" functions from my other files?

Sponsored Content