user4550164
user4550164

Reputation:

How to load partial HTMLs from another HTML?

I'm writing a book using HTML. If I write it in one html file, the whole code becomes long, so I want to save each chapters to different files and load them in main html. I mean there are files like chapter1.html, chapter2.html, ... and I want to include the contents of them in the other file main.html.

Is this possible?

Upvotes: 3

Views: 1941

Answers (3)

Thusitha Wickramasinghe
Thusitha Wickramasinghe

Reputation: 1103

If you wish to do this dynamically. you can use javascript instead of <iframe>. Save the HTML content you want to include inside content.html

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("data-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("data-include-html");
          includeHTML();
        }
      } 
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}
</script>

You can Add it to the HTML page Later like below.

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

Upvotes: 4

MeFisto94
MeFisto94

Reputation: 157

That depends on what you want to achieve. In general it's not bad to split the content by Chapters and just link to them. That way the reader isn't overwhelmed and if the book is large it reduces loading time.

Where and how do you want to publish that book? HTML provides multiple means to do what you want (Frames and iFrames, both not that "cool" nowadays), however if you're using some Server Side Scripting (like a CMS), you could use other means there.

Or you could have seperated html files and then use some simple concatenation (like with batch/linux shell) to generate a the big output html then.

Upvotes: 1

Xantium
Xantium

Reputation: 11605

You could use iframe to embed each page into main.html

For example:

<iframe src="chapter1.html"></iframe>
<iframe src="chapter2.html"></iframe>

You could also create it into a slideshow, so that it looks more like a book.

Upvotes: 2

Related Questions