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.

Answer from lolo on Stack Overflow
🌐
W3Schools
w3schools.com › howto › howto_html_include.asp
How To Include HTML
Including HTML is done by using a w3-include-html attribute:
🌐
W3Schools
w3schools.com › w3js › w3js_html_include.asp
W3.JS HTML Includes
HTML includes are done by JavaScript. Make sure your page has w3.js loaded and call w3.includeHTML():
🌐
GitHub
gist.github.com › h5ng › 8b072af9c730591328b91c6f2d98b371
w3-include-html · GitHub
w3-include-html. GitHub Gist: instantly share code, notes, and snippets.
🌐
Reddit
reddit.com › r/learnprogramming › html5 - why does my w3-include-html tag not work?
r/learnprogramming on Reddit: HTML5 - Why does my w3-include-html tag not work?
November 1, 2016 -

I want to include html code (a header) in another html page (index page).

Using php (include, echo) does work, but why does the tag w3-include-html not work :/.

I used it like this:

<div w3-include-html="path/name/info/htmlcode"></div>

Reference: http://www.w3schools.com/w3css/w3data_includes.asp

Top answer
1 of 4
9

Simple way would be to put the header part in a separate html file.

Now load this file in html code using jQuery load function like

$("#headerDiv").load("header.html")

Know that, this will require web server because load function sends a request to server.

Check out the code sample:

demo.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> 
   $(function(){
    $("#headerDiv").load("header.html");
   });  
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>

header.html

<div >
    <a>something</a>
    <a>something</a>        
</div>
2 of 4
5

That is called HTML includes, and YES, it is possible

<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
  myHTMLInclude();
  function myHTMLInclude() {
    var z, i, a, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
      if (z[i].getAttribute("w3-include-html")) {
        a = z[i].cloneNode(false);
        file = z[i].getAttribute("w3-include-html");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
            a.removeAttribute("w3-include-html");
            a.innerHTML = xhttp.responseText;
            z[i].parentNode.replaceChild(a, z[i]);
            myHTMLInclude();
          }
        }      
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
      }
    }
  }
})();
</script>

NOTES

HTML doesn't have a simple include mechanism (except for frames like iframe, which have side effects).

A better solution would be to use Server-Side includes, which is the preferred way of adding common parts to your document, on the server, of course.

Find elsewhere
🌐
GitHub
github.com › validator › validator › issues › 625
[Suggestion] w3-include-html attribute recognition · Issue #625 · validator/validator
November 23, 2017 - It occurred in my code at a line with: <div w3-include-html="../nav.html"></div>. There could be something that says Attribute "w3-include-html" should be replaced by using an "<iframe>" instead of "div".
Author   scoutchorton
🌐
Webdevable
webdevable.com › w3schools › w3js › w3js_include.html
W3.JS Includes
HTML includes are done by JavaScript. Make sure your page has w3.js loaded and call w3.includeHTML():
🌐
Experts Exchange
experts-exchange.com › questions › 29048402 › how-to-insert-html-into-html-file.html
Solved: how to insert html into html file | Experts Exchange
December 14, 2016 - <!DOCTYPE html> <html> <script src="https://www.w3schools.com/lib/w3.js"></script> <body> <div w3-include-html="content.html"></div> <script> w3.includeHTML(); </script> </body> </html>
🌐
Webdevable
webdevable.com › w3schools › howto › howto_html_include.html
How To Include HTML
Tabs Dropdowns Accordions Convert Weights Animated Buttons Side Navigation Top Navigation JS Animations Modal Boxes Progress Bars Parallax Login Form HTML Includes Google Maps Loaders Tooltips Slideshow Filter List Sort List · HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML. Read More » ... Your message has been sent to W3Schools.
🌐
Stack Overflow
stackoverflow.com › questions › 75392783 › using-w3-include-html-breaks-some-tags-and-js-scripts-stop-working
Using w3-include-html breaks some tags and JS scripts stop working
<!DOCTYPE html> <html lang="en-US"> <head> <!-- <link rel="icon" type="image/png" href="/icons/terminal16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="/icons/terminal48x48.png" sizes="48x48"> --> <div w3-include-html="modules/header.html"></div> </head> <body> <!-- ...
🌐
Sololearn
sololearn.com › en › Discuss › 3233556 › how-can-i-inherit-the-contents-of-one-html-file-into-another
How can I inherit the contents of one html file into another? | Sololearn: Learn to code for FREE!
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <div w3-include-html="first.html"></div> <div w3-include-html="second.html"></div> </body> </html> 17th Aug 2023, 7:25 PM · JaScript · + 5 · Евгений , We simply have different opinions.
🌐
Quanzhanketang
quanzhanketang.com › howto › howto_html_include.html
How To Include HTML
Color Converter Google Maps Animated Buttons Modal Boxes Modal Images Tooltips Loaders JS Animations Progress Bars Dropdowns Slideshow Side Navigation HTML Includes Color Palettes ... Your message has been sent to W3Schools.
🌐
TutorialsPoint
tutorialspoint.com › how-to-include-another-html-file-in-an-html-file
How to include another HTML file in an HTML file?
Includes a wrapper DOM with the attribute w3-include-html having the new HTML file name as the value.
🌐
Reddit
reddit.com › r/learnprogramming › opinions on this script?
r/learnprogramming on Reddit: Opinions on this script?
January 7, 2016 -

I found a script by w3schools that lets you add HTML to an HTML file from an external HTML file, and I was wondering what more experienced programmers though of it. https://www.w3schools.com/w3css/w3data_includes.asp

For example, if I don't want to copypasta my header to every page on my site, I can type <header w3-include-HTML="header.html"></html> instead. The script inserts the code from header.html as a child of this header tag.

You have to include a script tag at the bottom of the body calling the w3IncludeHTML() function to get it to work. I do not know if the script works when this script tag and the external inclusion tag are not siblings of each other, or if it works when the script is not at the bottom of the body tag. However, from the testing I've done in brackets, it works wonderfully and is very easy to use.

I'm just not sure how efficient it is / if it falls under the negative side of w3school's reputation.

What do others think of this script? Are there better, simpler ways to do this, other than using stuff like iframe?

Top answer
1 of 2
2

It's not that bad if it gets the job done. Generally however, if you're looking to do this sort of thing then you do it server side, because it is much faster (around 2-3x faster).

If you break down what is happening, your file is downloaded, and that html file says to download a script file, so it makes another request. then once it downloads the script, the script says to make another request to download the missing html. If you put all the html, js, and css together on the server, only one request needs to be made (it can even be cached for more speed).

So in all its completely fine to use on your own site, but is generally frowned apon for large sites.

If you want an alternative then you'll need to say which webserver you're using.

2 of 2
1

So, let's look at how w3 implemented this:

function w3IncludeHTML() {
  var z, i, elmnt, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          elmnt.innerHTML = this.responseText;
          elmnt.removeAttribute("w3-include-html");
          w3IncludeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }
}

The first thing that jumps out at me is this:

z = document.getElementsByTagName("*");

That grabs every element on the page. OK for small sites, but if you have lots of elements, this is not great. If your tests don't show it to be inefficient, it's because it's too small of a test case.

Then it loops through every element, checking to see if it has a non-standard attribute called `w3-include-html'.

For the first one it finds, it starts an AJAX request to download the contents of the referenced file, then returns. So only the first element that has the w3-include-html will actually be set. Also note: if your server is slow to respond with the referenced file, the div that's supposed to have that content will be blank with no indication of loading or that content is coming.

But wait! In the callback for the AJAX request, once the HTML comes back, it re-runs the w3IncludeHTML function. Which means this whole process starts over again; over and over until there's no elements with that attribute left on the page.


IMO, this is a bit of a messy way to do "includes". There might be a better way to do what you're asking about.

First, are you using a "back end", or is this front-end only? Are you using PHP/Django/Node.JS/ASP.NET/anything like that? If you are, each has its own way of including partial content on a page that won't involve another ajax request to the server; it would be included on the server-side and sent back to the client as one file.

If you still want to proceed with an include mechanism like this, I'd recommend you write it yourself. You can do better than they did, and it's really just one function.

What I'd recommend if you go down this route: use data attributes. You can query nodes by their data attributes, so you don't have to pull in every node and check for it. You can also use an ID (or even just capture the HTML node itself in your closure) so you don't have to return and have your callback keep chaining these calls; you could kick off all the include calls the first time and not re-call it (unless you wanted to support nested includes).

That's what I'd do.