Handling SVG is hard
Posted on 2015-04-13
SVG is a pretty neat image format. But it’s not as easy to implement in a web page.
Many different gotchas to watch out for, browser support is not totally there yet. Here are a few things I remember having to deal with.
<img>
tags aren’t the best way to inline images- Inlining the SVG XML directly in the page works best, but would increase the payload significantly since I have table of the same images
- I wanted to use the least JavaScript possible
- It needed to work on all recent browsers.
There were two steps. First, I wanted to use as much of SVG’s capabilities as possible, including styling. Since I wasn’t inline the SVG, I couldn’t
style it using CSS in my HTML page’s source. Therefore, I created an IHttpHandler
to modify a base SVG file with some extra classes.
Then, on the client side, I implement some JavaScript to add hover functionality.
Here’s the IHttpHandler
:
The Web.config
file must be modified:
And here is an AngularJS directive for the JavaScript:
The IHttpHandler
receives requests for all SVG files. It parses the file name and looks for class names in the format svg-file-name.class-names.svg
. I could have used the query
string, but browsers will usually understand a query string to mean that the file cannot be cached properly.
To display an SVG, it’s a simple matter of using <object>
:
I had to do a tiny bit of CSS for clickable-svg
to work, otherwise, the mouse pointer doesn’t react properly: