RobinBerjon

Force SVG — Forcing Browsers to Render SVG

Making a Render They Can't Refuse

Tech, Essay |

[UPDATE 2010-09-21] The most recent version of the code is now on GitHub, as part of the SVG Boilerplate project.

SVG has long been available in modern browsers, but it is nevertheless underused. While people often blame Internet Explorer for that sorry state of affairs (something which Brad Neuberg's excellent SVG Web project aims to address), I believe there is another reason: SVG cannot be embedded in regular HTML sent using the text/html media type as even browsers that support it won't render it. This forces people to use XHTML sent as application/xhtml+xml, which in turn pops up a download dialog in IE. This means that nice SVG effects that could degrade gracefully to IE (in the same way that unsupported CSS does) aren't possible.

Well no more. Using the ForceSVG library you can force modern browsers to render SVG in text/html, without enabling anything special. In fact, the site you're looking at right now is using it [UPDATE: this site no longer uses it, but it still certainly could].

The trick to accomplish this is almost as simple as (where svg is the SVG element one wishes to force to render):

var div = document.createElement("div");
div.appendChild(svg.cloneNode(true));
var dom = (new DOMParser()).parseFromString(div.innerHTML, "application/xml");
svg.parentNode.replaceChild(document.importNode(dom.documentElement, true), svg);

An in fact my first go at this used just that, and just worked. But it only worked because the example that I was testing with was SVG that only contained lower-case element names — the second that I tried using it with varying-cased elements (in this instance filters) things fell to pieces. Because of that, the majority of the code in the library concerns itself with walking the SVG tree and renaming elements and attributes that have been flattened to lowercase. There may be a simpler way to this, but this one works so I'm happy with it for now.

So go grab it and start hacking on those wicked cool HTML+SVG demos!