Home

2 minute read

Include HTML inside of HTML

Tony Lea

Include HTML inside of HTML

I was searching for a simple solution that would allow me to include an HTML partial inside of another HTML file without a server-side language or the need for a javascript build process.

When I searched the inter-webs for an easy solution, I stumbled upon this CSS Tricks page titled: "The Simplest Ways to Handle HTML Includes"

include-html.png

On this page, chriscoyier (the creator of CSS-Tricks), wrote a snippet that looked like this:

...
<body>
   <include src="./header.html"></include>

   Content

   <include src="./footer.html"></include>
</body>
...

And, the next line stated that this was not Real, but he wish it was. The rest of the article explains different frameworks and languages for accomplishing this.

Well, that made me wonder why this wasn't possible, and that sent me down a small rabbit hole 🐇 of discovery and creation. I created a simple script that you can include in your HTML page to make this possible.

The Script

I published the script on NPM here: https://www.npmjs.com/package/htmlincludejs, and it's as simple as including the following script in your page:

<script src="https://unpkg.com/htmlincludejs"></script>

And now you can render HTML inside of another HTML file using the following tag:

<include src="./nav.html"></include>

Super 👏, you can see a really quick example from this codesandbox below.

Checkout our latest product - the ultimate tailwindcss page creator 🚀

Here is the code inside that sandbox:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Includes</title>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/htmlincludejs"></script>
  </head>

  <body>
    <include src="./nav.html"></include>
  </body>
</html>

Let's learn how simple this is to implement by hand.

How it Works

The way this works is actually pretty easy. Take a look at the unminified script below:

let includes = document.getElementsByTagName('include');
for(var i=0; i<includes.length; i++){
    let include = includes[i];
    load_file(includes[i].attributes.src.value, function(text){
        include.insertAdjacentHTML('afterend', text);
        include.remove();
    });
}
function load_file(filename, callback) {
    fetch(filename).then(response => response.text()).then(text => callback(text));
}

All that we are doing is looping through any <include> tags and then we are doing a simple javascript fetch to retrieve the contents of each partial and place it after the <include> tag. We then remove the include tag and we are good to go 😉.

Examples

Here are a few more CodeSandbox examples below.

You can see that we can also include some simple [AlpineJS] magic into our partials, and the javascript still works :)

How about another example that uses some TailwindCSS.

Conclusion

If you ever need a simple solution to include HTML partials inside of another HTML file, you may want to reach for this simple solution.

Happy coding ✌️