Svg image element not displaying in Safari

I just discovered this same problem when I checked an app I was working on in Safari, after having been using Chrome most of the time. I wrote this bit of TypeScript/jQuery code (easily enough turned into plain JavaScript) to solve the problem:

export function setSvgHref(elem: JQuery, href: string) {
  elem.attr('href', href);

  if (isSafari()) {
    elem.each(function() {
      this.setAttributeNS('http://www.w3.org/1999/xlink', 'href', href);
    });
  }
}

I think there are two problems here:

  1. You haven't said anything about how large your SVG image is. As a rule, you should at least include a viewBox attribute in the <svg> tag. For example:

    <svg width="250" height="250" viewBox="0 0 250 250" ... >
    
  2. The other problem is that Safari isn't particularly brilliant at rendering SVGs. However, it tends to do better when you embed them with an <iframe> or <object> tag instead of using <img>. For example:

    <object data="image.svg" type="image/svg+xml"></object>
    

    Also, make sure your server is delivering SVG content with the correct MIME type (Content-Type: image/svg+xml), as this can cause problems too.


So give this a try:

HTML source:

<!DOCTYPE html>
<html>
<body>
<h1>My first SVG</h1>
<object data="image.svg" type="image/svg+xml"></object>
</body>
</html>

image.svg:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="250" height="250" viewBox="0 0 250 250"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
      <rect x="50" y="50" width="100" height="100" style="fill:blue"></rect>
      <rect id="foo" x="50" y="150" width="500" height="500" style="fill:green"></rect>
     <image x="50" y="10" width="200" height="200" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="></image>
</svg>

In the <image> tag inside the svg element, href works fine in Chrome. To work in older versions of Safari, you need xlink:href. (Also applies to the <use> tag.) Keep in mind xlink:href is deprecated and is being replaced by href. However, it was not supported until Safari 12.

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/href

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ...>
    <image href="data..." xlink:href="data...">
</svg>

Tags:

Safari

Svg