1

It is possible to synchronously create a <svg> element with Javascript that is a copy of a SVG file?

I have a small SVG in an external file called cursor.svg located in a folder called svg. So its relative path to my base HTML file is svg/cursor.svg. The SVG is very simple:

<svg id="cursor">
    <rect x="50" y="20" rx="20" ry="10" width="10" height="150" style="fill:red;stroke-width:0" opacity="0.75">
      <animate attributeName="opacity" begin="indefinite" values="0.75;0" dur="1s" repeatCount="1" />
    </rect>
</svg>

I would like to be able to have a createSvgNode() function that simply returns a SVG node that is a copy of the one within cursor.svg. (so that the function code would remains the same even if the SVG file changes) But I want it to be synchronous. Is there a possible solution for this? Maybe by loading the cursor.svg file in the HTML DOM?

Thanks for any suggestion.

PhilippeC
  • 51
  • 1
  • 3
  • I don't understand, are you trying to copy an svg element that is already in the DOM or are you trying to load an svg file with JavaScript and then place it in the DOM? – zero298 Apr 20 '18 at 15:02
  • Possible duplicate of [Loading a SVG file with svg.js](https://stackoverflow.com/questions/15911246/loading-a-svg-file-with-svg-js) – zero298 Apr 20 '18 at 15:19
  • "Synchronous" is not a sensible requirement, as long as your SVG is a file separate from your HTML file. To get it from the server to your browser, you need a separate request. There is no method that would block the Javascript thread for the (unpredictable) time it takes until the response arrrives; they all work asynchronously to provide for that delay. – ccprog Apr 20 '18 at 17:22
  • @zero298 (second comment): I do not think this question is a duplicate, as my question is not about the svg.js framework. – PhilippeC Apr 21 '18 at 15:15
  • @zero298 (first comment): I am looking for javascript way to create copies of a SVG contained in a file. – PhilippeC Apr 21 '18 at 15:16
  • @ccprog is there no way to import SVG file directly in the DOM so that I do not have to wait for the callback? Something like using an ``element in HTML ? – PhilippeC Apr 21 '18 at 15:17
  • Am I trying to make this more complicated than it is? If you are just trying to take an SVG file and put it directly into the DOM, does using `` work? – zero298 Apr 21 '18 at 15:24
  • @PhilippeC Amounts to the same thing. (It's `` btw). You have to wait for the `load` event of the object and can access the DOM of the file only in the listener callback. – ccprog Apr 21 '18 at 15:26

0 Answers0