When I try to use a warehoused SVG image in an <img> tag, nothing shows up.

0 votes
asked Mar 8, 2015 in HTML and CSS by q2aadmin (6,015 points)
edited Mar 8, 2015 by q2aadmin

My code for this is pretty simple, it looks something like this:

<img src="http://my.site.com/path/to/images/my_image.svg" />

When I preview the page it just shows up as blank.

1 Answer

0 votes
answered Mar 8, 2015 by isaiah (13,745 points)
edited Mar 11, 2015 by q2aadmin
Best answer

Because an SVG is a sort of small program that draws an image, SVG has limitations like Javascript about loading resources from remote locations to prevent cross-site scripting attacks. What does that mean for you? It means that you can only load an SVG from the same website as the one that's displaying it.

So, if you use an image tag like:

<img src="http://www.mysite.com/path/to/images/my_image.svg">

This will work as long as the both the image and the page are on www.mysite.com

update: it will also work fine on your own machine and within RapidWeaver preview (thanks Joe).

If you do need to warehouse your files on another domain you can use the <object> tag instead of the <img> tag. Objects are contained in their own little sandbox so they don't have the same limitation. So something like this should always work:

<object data="http://my.site.com/path/to/images/my_image.svg" type="image/svg+xml"></object>

There are, of course, other limitations of the <object> tag. It's slower. It eats a bit of memory. And it can't be styled with CSS in nice ways that an <img> tag can.

commented Mar 10, 2015 by joeworkman (1,035 points)
Why use an object tag? Just use the `<img>` tag with the full warehoused image url...

<img data="http://my.site.com/path/to/images/my_image.svg" alt="My Image"/>

This works fine in RapidWeaver. I use it all of the time.

(could not figure out how you got all your pretty formatting)
commented Mar 10, 2015 by q2aadmin (6,015 points)
the img tag imposes the "same origin policy" on svg content. the object tag avoids those.

here's details:

i think the policy is different for local files.

you only get markdown syntax on full answers -- not on comments. why? encourage answering, discourage chatter.
commented Mar 11, 2015 by joeworkman (1,035 points)
Yeah. I was assuming that most users are going to host the image on the same domain as their website. For local previewing, the policy is ignored.
commented Mar 11, 2015 by q2aadmin (6,015 points)
Updated the answer to note that it works on the local machine. And to use a fully qualified URL.