Including content from other files in your HTML (“HTML Includes”)

Nice find by Scott Jehl from Filament Group: Instead of fetching files over XHR and then injecting their contents, you can also use an iframe + leverage its onload event to include the contents of any other file directly into the current web page.

<iframe
  src="signal.svg"
  onload="this.before((this.contentDocument.body || this.contentDocument).children[0]);this.remove()"
></iframe>

The example above loads up a .svg, but you can also use it to include other pieces of markup. Above that you can combine it with [loading="lazy"].

This is “Server Side Includes” all over again 😅

HTML Includes That Work Today →

Sandboxed iframes

<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
    src="https://platform.twitter.com/widgets/tweet_button.html"
    style="border: 0; width:130px; height:20px;"></iframe>

The sandbox attribute of the iframe element allows us to tighten the restrictions on framed content. We can instruct the browser to load a specific frame’s content in a low-privilege environment, allowing only the subset of capabilities necessary to do whatever work needs doing.

Play safely in sandboxed iframes →