SVG Absolute Pathing for `xlink:href` Attribute Not Working

Nick Zuber picture Nick Zuber · Aug 9, 2016 · Viewed 8.2k times · Source

So I have a single SVG file that holds a collection of different paths:

<!-- icons.svg -->

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <path id="foo" .../>
  <path id="bar" .../>
  ...
</svg>

and within my webpages, I use these SVG icons:

<!-- index.html -->

<svg viewBox="0 0 256 256">
  <use xlink:href="icons.svg#foo">
</svg>

and this works just fine and exactly how I intend -- we select the SVG with the id foo from the icons.svg file.

Now, if I try to give the xlink:href attribute for the <use> tag an _absolute_ path to my icons.svg file, it fails and returns nothing and seems to be unable to find the file..

<svg viewBox="0 0 256 256">
  <use xlink:href="http://localhost:8080/icons.svg#foo">
</svg>

It's important to note that the absolute path is correct.

The documentation on xlink seems to suggest that absolute paths are valid values, which makes me wonder why it doesn't work here for me -- am I missing something?

Is there an alternative approach I should be considering? Is this currently not the approach I want to take to achieve something like this?

Answer

Kaiido picture Kaiido · Aug 9, 2016

You have to be sure you are loading your external svg file from the same protocol and port, otherwise, browsers will block the request, according to the same-origin policy.

Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.

(emphasize mine)