SVG `use` with External Source

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

There is another, newer article on this subject that covers some newer information.

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>
</svg>

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

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.