0

I have some SVG objects displayed within bootstrap tabs

<object
 className="test_card"
 type="image/svg+xml"
 data={"http://127.0.0.1:8000/static/images/card_layout.svg"}>
    Your browser does not support SVGs
</object>

The problem is that everytime I change the active tab, there is a short delay before the SVG images get displayed, like the page is loading them.

If I use <img/> to display the SVGs, they stay loaded and show instantly when I activate the tab, but I need to be able to modify some of the SVG content dynamically, so I can't use that.

How can I keep the SVG pictures loaded?

Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78

2 Answers2

0

The svg images and icons are slow. You need to convert them in web fonts to improve performance. Check out this article for more details. http://frozeman.de/blog/2013/08/why-is-svg-so-slow/

Nikola Andreev
  • 624
  • 4
  • 18
  • Thanks for the article. It's interesting but I don't want the SVG pictures to load faster, I want them to stay loaded so that it displays instantly – Ryan Pergent Jan 21 '18 at 11:00
0

I came up with a solution. Instead of objects, I load the svg file into a string, and inline it dynamically in my html.

I get the SVG string with a jquery AJAX call:

$.get("/static/images/cardLayout.svg?",
            (data) => {
                svgString = new XMLSerializer().serializeToString(data.documentElement);
            }
        );

This gives me the string representing the SVG.


From there, in react, I am using:

<div dangerouslySetInnerHTML={{__html: svgString}} />

Which displays the same thing that using <object>, except that the svg is now inlined and doesn't get unloaded each time I change the active tab.


If you're not using React

I didn't test it, but with pure JS I think you can transform a string into a dom element using the answer to this question: Converting HTML string into DOM elements?

Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78