Is there a way to asynchronously load parts of a large SVG shape?

410 Views Asked by At

I am trying to develop a website consisting of a geographic map using svg, with data derived from OpenStreetMap. Since it will be large and will be accepting transformations (zooming and moving), only a part of it will visible on the screen. So, for performance issues, probably it will be necessary to find a way to asynchronously load parts of it. Is there a way to do this? (e.g., like CATiledLayer of iOS)

How do websites like Google Maps do this?

1

There are 1 best solutions below

4
gazdagergo On

You have to use the svg inline and not as an image reference. This way you will be able to manipulate the image parts as a DOM elements with javascript.

// adding a black circle after 1 sec
setTimeout(() => {
  var svgNS = "http://www.w3.org/2000/svg"
  var myImage = document.createElementNS(svgNS,"image")
  myImage.setAttributeNS(null,"x",20)
  myImage.setAttributeNS(null,"y",20) 
  myImage.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","https://picsum.photos/200/200")
  document.getElementById("mySVG").appendChild(myImage)
}, 1000)
<!-- existing svg image -->
<svg id="mySVG">
  <circle fill="red" cx="20" cy="20" r="20" />
  
</svg>

In the above example an image is being added to an existing svg. Thanks for Alex Moanga and Daveman for the js snippets.