Inline an SVG file in HTML, declaratively & asynchronously!

An experiment by Scott Jehl of Filament Group

Here is an inline (embedded) SVG graphic. It was loaded from an external file called signal.svg.

To load and embed the SVG file, this page includes the following markup:

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

However, if you inspect the graphic above using developer tools, you'll see the SVG markup for the icon, inlined right in the HTML DOM, with no iframe element to be found. This is because the code uses an iframe to load the SVG file, and an onload event to inject the iframe's document just before the iframe in the HTML, before deleting the iframe itself.

Why would we want to do this?

Well, inlining (or "embedding") SVG makes it possible to manipulate its elements with CSS and JavaScript most flexibly. Unfortunately, there's no simple way to just inline an SVG file. I think it'd be particularly nice to be able to declaratively inline an external SVG file using HTML alone. This approach essentially does that. What's also nice about this is that it allows for browser caching of the SVG, so many pages can use the same inline SVG without downloading it each time.