SVG `use` with External Source

Published by Chris Coyier

Inline SVG is an awesome way to use SVG because, among other reasons, the individual shapes that make up the graphic can be scripted and styled. The shapes are right in the DOM. But does that mean we have to define those shapes right in the HTML on every page? Nope, we can <use> to reference them from elsewhere. Ideally, that "elsewhere" is an external file, because that means that file can be cached by the browser, efficiency!

Here's what I mean:

<!-- `<use>` shape defined ON THIS PAGE somewhere else -->
<svg viewBox="0 0 100 100">
   <use xlink:href="#icon-1"></use>

<!-- `<use>` shape defined in an EXTERNAL RESOURCE -->
<svg viewBox="0 0 100 100">
   <use xlink:href="defs.svg#icon-1"></use>

So yeah: external resource = the way to go.

But, the external resource way doesn't work in any version (up to 11 tested) of Internet Explorer. Even the ones that do support inline SVG: 9, 10, 11.

Fortunately, Jon Neal has a clever solution. It's a little script called SVG for Everybody. The idea is this: just use <use> as if it works, and the script will handle it in IE 9, 10, 11. A polyfill, except just for this scenario (it doesn't make this work anywhere that doesn't already support inline SVG use).

It works like this:

  1. If the browser is IE 9, 10, or 11 (User Agent sniff, but that's the whole point here).
  2. Ajax for the SVG file referenced
  3. Find the needed bit, based on the ID referenced (e.g. #icon-1)
  4. Inject that into the <svg> on the page

It totally works.

I think inline SVG is damn useful and this (tiny) script means you can use it in a more responsible (cacheable) way.

Wanna learn more about SVG?

I have a full course available called Everything You Need to Know about SVG that covers the whole spectrum of SVG from the perspective of a web designer and front end developer.