Snap.load() external SVG fails to Load

Marcatectura picture Marcatectura · Nov 12, 2013 · Viewed 19.7k times · Source

PROBLEM: I'm using Snap.svg to create some basic interactive graphics, but for some reason I can't get my external SVG file to load using Snap.load(). I've pulled code straight from the tutorial at snap.io and checked and double-checked the docs. My SVG file renders in the browser fine, it just doesn't display inside the Snap SVG. Other shapes (i.e. not pulled in using Snap.load() ) do display.

CODE: I've boiled my example down to the most simple HTML and SVG files imaginable, and the Snap.load() method still isn't working for me. Does anyone see what I'm missing?

HTML:

<head>
  <style media="screen">
            #svg {
                width: 300px;
                height: 300px;
            }
  </style>
  <script src="snap.svg-min.js"></script>
  <meta charset=utf-8 />
</head>
<body>
  <svg id="svg"></svg>
  <script type="text/javascript">
    var s = Snap("#svg");
    Snap.load("svgtest.svg");
  </script>
</body>

SVG (originally exported from Illustrator):

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="100px" height="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<rect x="14" y="33" fill="#2BB673" width="70" height="30"/>
</svg>

UPDATE: Updated the code as per @Ian's suggestion -

var s = Snap("#svg");
Snap.load("http://www.w3.org/TR/SVG/images/struct/Use01.svg", onSVGLoaded ) ;

function onSVGLoaded( data ){ 
    s.append( data );
}

- but still no display of external SVG. I tried using an SVG from w3.org just to be sure it wan't a problem with the file itself or my domain.

Answer

Ian picture Ian · Nov 12, 2013

The load function takes a callback, as loading can take some time. So I think you would do something like the following...

var s = Snap("#svg");
Snap.load("svgtest.svg", onSVGLoaded ) ;

function onSVGLoaded( data ){ 
    s.append( data );
}

Edit: There may be some access control issues if not accessing from the same server as the script, check the console log for any errors.