4

I'm using D3 to render a few hundreds of svg elements. However, only few of them are visible simultaneously in the viewport.

So I thought possibly I could gain a performance boost by removing those elements which are off screen and recreate them when they are scrolled back into view.

Is this a reasonable assumption?

Are there any tools available for such a thing?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Ofri
  • 474
  • 5
  • 13

3 Answers3

2

If you're just concerned with them being invisible, you could instantiate the ones you don't need out of bounds of the element, and then transform("translate(x, y)") them into view when you need them.

If you don't want them to exist until you need them, store their attributes (including initial position and whatever else you need) in an object array and instantiate them onscreen in their initial position. This would offer the better performance advantage.

  • well yes, this is kinda what i had in mind. do you know of any library maybe which does that? that is reducing the amount of dom elements by keeping only the elements which are visible and removing the ones which are not? – Ofri May 09 '15 at 00:36
  • @Ofri If you're able to designate the unwanted dom elements as separate from the ones you want visible (e.g. giving them a separate class) you can remove them with jQuery. – Gerald Shaeffer May 09 '15 at 02:11
1

More generally, take a look at defs and use for element or group reuse. You might generate a "pool" of objects and apply translation to position them inside or outside the viewport, for instance.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
  • thanks. my goal though is to reduce the number of dom elements, and from what I understand using "use" would still render the elements... – Ofri May 09 '15 at 00:30
1

You can just set the display property to none for any SVG element you want to hide.

document.getElementById("unwanted").style.display = `none`;
<svg>
    <circle id="wanted" cx="50" cy="50" r="50" fill="red"/>
    <circle id="unwanted" cx="100" cy="100" r="100"/>
</svg>
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
  • 1
    My goal is to save in dom elements. will setting display to 'none' help with performance? – Ofri May 14 '15 at 14:43
  • 2
    Ah sorry. I see I didn't read your question properly. It is possible `display: none` might help, but I would have expected most SVG implementation will be checking whether an element is onscreen anyway. It's possible that you will be doing a lot of work for no benefit, or even a slight cost. – Paul LeBeau May 14 '15 at 16:15