Unfortunately, it was both JS-dependent and never really went anywhere.
Over the next few days, we’ll look at four ways you can use HTML includes today. Let’s dig in!
For this lesson, let’s assume we have an
index.html file with some HTML in it.
<h1>Hate the complexity of modern front-end web development?</h1> <p>Me too! I send out a short email each weekday on how to build a simpler, more resilient web. Join over 13k others.</p>
We also have an external HTML file,
about.html, with a bit more markup in it.
We want to include the HTML from
about.html on the
index.html (and probably a few other places, too).
Option 1: an iframe (seriously!)
My favorite approach to this problem comes from the Filament Group.
First, you include an
iframe that points to the remote content.
Next, you add an
iframe loads, we want to grab the
iframe. Then, we’ll use the
Element.children property to get all of the child nodes.
<iframe src="about.html" onload="this.before(...(this.contentWindow.document.body||this.contentWindow.document).children)"></iframe>
As one last bit of cleanup, we should use the
Element.remove() method to remove the
iframe from the UI.
<iframe src="about.html" onload="this.before(...(this.contentWindow.document.body||this.contentWindow.document).children);this.remove()"></iframe>
You can download the source code on GitHub.
Over the next few days, we’ll look at a few web component options, as well as how to do this on the server.