Making Inline SVG Play Nice in Legacy IE
Last week I was tearing my hair out trying to track down why the latest version of this site was rendering so badly in legacy versions of Internet Explorer.
It was particularly annoying because I’m such a strong adherent to progressive enhancement. I try to build my projects with the basics first, then layer on the more sophisticated bits. That usually makes legacy browser support easier, if not trivial. The fancy stuff typically doesn’t render or get in the way, and foundation-level content still works in the accounting department’s crusty old browser of choice. But not this time.
Specifically, jQuery was going a little nuts trying to traverse the DOM in IE8 or older, returning weirdly inconsistent results. Here’s a sampling of some queries and their pass/fail results:
$('footer[role="contentinfo"]')= failed$('div[role="contentinfo"]')= worked$('div[role="contentinfo"] nav')= failed$('footer')= worked
After doing a few reductions I found the issue, and it wasn’t at all what I expected: inline SVG. Specifically, there are two components of inline SVG that seem to scramble legacy IE’s brain:
- The XML namespace attribute: Removing the
xmlnsattribute fromsvgelements (or simply setting its value to “ ”) returns sanity to the DOM. To be clear, I do not recommend doing this. Thexmlnsattribute is there for a reason, and I have no idea how removing it might affect other browsers. Interestingly, related attributes such asxmlns:xlinkdon’t have a similar negative impact. Only the default namespace attribute does this. - Self-closing elements inside inline SVG: The presence of self-closing child elements in inline SVG (like
<circle />or<path />) consistently triggers this issue in IE8 and lower. Fortunately, this one has an easy fix. Simply change self-closing child elements in your SVG to have a separate closing tag. So instead of<circle />, use<circle></circle>.
If you’re running into this issue, I recommend fix #2. It’s a simple, valid way to bulletproof inline SVG for older versions of Internet Explorer. This allows it to degrade gracefully, failing quietly if browser support isn’t present, rather than causing errors and breaking the user experience.
Today I’m very happy to announce that