33

I have a html "head" template and a navigation template that I want to include in all my other html files for my site. I found this post:

Include another HTML file in a HTML file

And my question is... what if it's the header that I want to include?

So for example, I have the following file structure:

 /var/www/includes/templates/header.html
                             navigation.html

header.html might look like this:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Test Portal</title>

 </head>

In a case like this, can I still follow the example in the other post where they create a div and populate the div via jquery?

Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70
Happydevdays
  • 1,982
  • 5
  • 31
  • 57

6 Answers6

41

Method 1:

I think it would be best way to include an html content/file into another html file using jQuery.

You can simply include the jQuery.js and load the HTML file using $("#DivContent").load("yourFile.html");

For example

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#DivContent").load("another_file.html"); 
    });
    </script> 
  </head> 

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

Method 2:

There are no such tags available to include the file but there are some third party methods available like this:

<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>

<body>

<div w3-include-html="content.html"></div> 

<script>
w3IncludeHTML();
</script>

</body>
</html>

Method 3:

Some people also used server-side-includes (SSI):

<!--#include virtual="a.html" --> 
Étienne
  • 4,773
  • 2
  • 33
  • 58
Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70
  • 2
    seems to be working for me – Happydevdays Aug 09 '16 at 19:57
  • 2
    Looks like Method 2 has been changed, here is a link to the latest documentation https://www.w3schools.com/w3js/w3js_html_include.asp. – mattruma Aug 15 '19 at 11:19
  • 1
    @mattruma, Possible, Its been 3 years I gave this answer. And as I said, Method 2 is just a third party plugin/method.. – Punit Gajjar Aug 19 '19 at 05:40
  • 2
    I gather #3 is C++ and not supported by my webserver (?), and I'm not a fan of #2 including an extra `.js` just for one function, but #1 worked great for me... once I [added a **callback**](https://stackoverflow.com/a/6762884/8112776) so code execution wouldn't continue until the file was fully loaded (since I needed to interact with the loaded elements immediately). – ashleedawg Dec 09 '19 at 19:52
18

Use <object> tag:

<object data="filename.html"></object>
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
  • 2
    Brilliant! Clean and simple. – Snowman Aug 22 '20 at 18:21
  • 1
    It shows a srollable window in a `body` tag surrounded by `html` tag, with `head`, so it creates a new `dom`. – Timo Oct 08 '20 at 06:53
  • 3
    Nice! One small limitation though, the CSS styling of the host page isn't applied to the inserted HTML text (at least not for me on Chromium 87.0/Ubuntu 20). Unless, the styling is included within the imported text. – Todd Dec 01 '20 at 01:20
  • 1
    It's not working, it start a flash emualtor – G. Ciardini Sep 04 '21 at 16:32
8

I needed to include many files. So I created the following script:

<script>
  $(function(){
    $('[id$="-include"]').each(function (e){
        $(this).load("includes\\" + $(this).attr("id").replace("-include", "") +  ".html");
    });
  });
</script>

Use div, for example, to put a placeholder for the insertion.

<div id="example-include"></div>

Created folder "includes" for all files I needed to include. Created file "example.html". It works with any number of includes. You just have to use the name convention and put all included files in the right folder.

Maxim Trushin
  • 121
  • 1
  • 2
5

Using HTML <iframe> tag.

I have faced similar problem , then I used

<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>
D_00
  • 1,440
  • 2
  • 13
  • 32
5

For anyone interested in a Web Component approach:

<html-include src="my-html.html"></html-include>

And the corresponding JS:

class HTMLInclude extends HTMLElement {
  constructor() {
    super();
    this.innerHTML = "Loading...";
    this.loadContent();
  }

  async loadContent() {
    const source = this.getAttribute("src");
    if (!source) {
      throw new Error("No src attribute given.");
    }
    const response = await fetch(source);
    if (response.status !== 200) {
      throw new Error(`Could not load resource: ${source}`);
    }
    const content = await response.text();
    this.innerHTML = content;
  }
}

window.customElements.define("html-include", HTMLInclude);

Note that it is possible to do some nice things with a shadow DOM to make sure styling of loaded content does not influence the outer page.

The above code is pretty "modern" JS and you might not want to use the above code directly without some polyfills/babel transpilation.

Floriaan
  • 171
  • 2
  • 4
  • How to query some elelment in my-html.html ? I cannot query element in that file because when we query, it does not appear in DOM – Cyan Coder Apr 19 '21 at 11:11
0

This is similar to another custom tag solution, but this one uses the text between the opening and closing tags as the include path/url. The other solution uses the src attribute instead.

<html-include> ./partials/toolbar.html </html-include>

The element implementation's a little trickier:

# -- ./js/html-include.js --

class HTMLInclude extends HTMLElement {
    constructor(src) {
        super();
        this.attachShadow({mode: "open"});
        if (src) { 
            this.textContent = src;
        }
        setTimeout(() => this._load());
    }
    async _load() {
        let src = this.textContent.trim();

        if (!src) {
            throw new Error("URL missing between <html-import> tags.");
        } 
        let rsp = await fetch(src);

        if (rsp.status != 200) {
            throw new Error(`Failed to load file (${src}) for <html-import>.`);
        }
        this.shadowRoot.innerHTML = await rsp.text();
    }
}
customElements.define("html-include", HTMLInclude);

The setTimeout() was necessary because this.textContent, if accessed too early, can include all the preceding text of the page (seen on Chrome/Chromium). Deferring the access fixes that.

This is what it looks like incorporated in a page:

<html>
    <head>
        <link rel="stylesheet" href="./css/index.css">
        <script type="text/javascript" src="./js/html-include.js"></script>
    </head>
    <body>
        <html-include> ./partials/toolbar.html   </html-include>
        <html-include> ./partials/side-menu.html </html-include>
        <html-include> ./partials/statusbar.html </html-include>
    </body>
</html>

CSS styles should be properly applied to the newly imported HTML.

This element can also be created from JS by passing it the URL to the import file.

let wgthost = document.getElementById("tgt");
wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));
Todd
  • 4,669
  • 1
  • 22
  • 30