35

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?

1
  • i dont see why it should not work like described in the link you provided. Commented Aug 8, 2016 at 20:22

6 Answers 6

42

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" --> 
Sign up to request clarification or add additional context in comments.

4 Comments

<!-- #include virtual=x.html --> seems to be working for me
Looks like Method 2 has been changed, here is a link to the latest documentation w3schools.com/w3js/w3js_html_include.asp.
@mattruma, Possible, Its been 3 years I gave this answer. And as I said, Method 2 is just a third party plugin/method..
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 so code execution wouldn't continue until the file was fully loaded (since I needed to interact with the loaded elements immediately).
22

Use <object> tag:

<object data="filename.html"></object>

4 Comments

Brilliant! Clean and simple.
It shows a srollable window in a body tag surrounded by html tag, with head, so it creates a new dom.
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.
It's not working, it start a flash emualtor
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.

Comments

7

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.

1 Comment

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
5

Using HTML <iframe> tag.

I have faced similar problem , then I used

<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>

1 Comment

this is raw html based solution, does not need to have dependency on Jquery. @Akash thanks
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"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.