include HTML code inside HTML pages using a custom tag load-html to load content dynamically

Usage | Annotated source | License


Start with your index.html

<!doctype html>
    <load-html src="helloWorld.html">Loading...</load-html>

Content inside <load-html> custom HTML tag is optional.

Create files helloWorld.html and linkToHomepage.html in the same folder.

<!-- helloWorld.html -->

<h1>Hello World</h1>

<load-html src="linkToHomepage.html"></load-html>
<!-- linkToHomepage.html -->

  This content was loaded by <a href="https://g14n.info/load-html">load-html</a>.

Import loadHtml function some how, for example, add the following tag to your index.html:

<script src="https://unpkg.com/load-html"></script>

Then invoke it on window load, for instance add the following snippet to your index.html:

window.addEventListener('load', function () {

Annotated source

Start with attribution comment: web site and license.

// https://g14n.info/load-html License: MIT

Just define a global loadHtml function.

function loadHtml () {

Select all load-html tags. Note the loaded attribute, used to achieve recursive loading.

  var nodes = document.querySelectorAll('load-html:not([loaded])');
  var toBeLoaded = nodes.length;

Fetch the HTML content for each node.

  nodes.forEach(function (node) {
    try {
      var loader = new XMLHttpRequest();
      loader.addEventListener('load', function loadHtml () {
        if (loader.status == 200) {
          node.innerHTML = loader.responseText;
        node.setAttribute('loaded', true);

Keep track of number of DOM nodes loaded, then try to repeat recursively.

        if (toBeLoaded == 0) {

Send request to fetch content.

      loader.open('GET', node.getAttribute('src'), true);

Store error, mark include as loaded.

    } catch (e) {
      node.setAttribute('error', e);
      node.setAttribute('loaded', true);

Export it as a global function.

window.loadHtml = loadHtml;