Robin Berjon

For Whom The Belle Trolls

Take That You Silly Browser!

Force SVG

This library offers a few methods that make it possible to force browsers that support SVG but don't render it in text/html context to do so.

It has two entry points: berjon.ForceSVG.forceAllSVG() that looks for all SVG content in a document and forces it all to render (as used by this site [UPDATE: this site no longer relies on it, but it still certainly could]) — you can pass in a Document object to apply it to a document other than the current one; and berjon.ForceSVG.forceSVG(svgEl) which takes an SVG element already in the document and forces it to render.

There is also an experimental fixCreateElementNS() which intends to install a wrapper around createElementNS() to make sure that it returns proper SVG elements in a text/html context — which isn't normally the case. I'll note though that I just hacked that but haven't tested it. It's a new methodology I'm working on based on a release-first approach to code.

There are some limitations one needs to be aware of: empty elements (e.g. <rect/>) don't work — you have to use the more expanded version (<rect></rect>) for it to work. Also, SVG elements cannot have a prefix. Neither of these limitations mean anything to SVG (an SVG implementation will render documents authored like this in the exact same way), and converting to it should be easy enough.

As a bonus, since this is HTML and therefore namespaces aren't welcome, the script works without namespace declarations for SVG or XLink needing to be made. Like it or not, this is similar to what Brad Neuberg did, and I think that in an HTML context it's the sensible option (note that if your HTML is really XML in disguise as mine tends to be, you can still declare the namespaces of course).

A few extra implementation details are provided in the original blog post announcing it.

You can see a quick and ugly demo of it. I've tested it in Firefox 3.5, Safari 4, and Opera 10 — but it may work in earlier versions. In Internet Explorer it should do basically nothing. The site you're looking at right now uses it, [UPDATE: used to use it, so you won't see the following] so if you see a bit of largely useless SVG in the bottom right corner then it's working for you.

You can download it here. It is distributed under the Artistic License 2.0. Use at your own risk. This is produced by myself and not as part of my consulting contract with Vodafone.