Best way to preset SVG image tags?

I am creating an SVG-based visualization that (partially) relies on displaying many images in quick succession. Images cannot be retrieved quickly enough from the network, so they must be preloaded.

I understand that SVG does not cache image tags, at least in major browsers. Therefore, JavaScript preloading librairies and methods (like this SO question ) will not work. (I could resort to using multi-level HTML img tags, but due to the features of my application I would like to stick to pure SVG as much as possible)

I see two options:

  • Encoding PNG image data as base64, storing it in memory as strings, and using strings to iteratively populate image tags with data:image/png;base64 .
  • Overlaying many SVG groups on top of each other with all but one of them on display: none or visibility: hidden and iteratively showing the corresponding group. However, I believe that it will not be possible to programmatically detect that all images have completed pre-loading.

What is the best way to preload image data? Perhaps I missed a simpler option.

+6
source share
1 answer

I'm not good enough at the basic mechanics of web browsers to find out if this will work with svg image tags, but I have had successful caching of images using the new Image ():

  //download low quality images var imageArray = [] for (var i = 0; i < 600; i++){ imageArray[i] = new Image(); imageArray[i].src = moviePath + (i + 1) + '.jpg.t'; imageArray[i].onload = function(){ var i = this.src.split(movieName + '/')[1].split(".")[0]; d3.select("#bar" + i).style("stroke", 'rgb(' + colors[i].rgb + ')'); } } 

To show the image, I just set the src of the displayed image to the one that was already loaded, and the browser loads it from my cache.

There is another little trick used later in - First display a low quality image and start downloading a high quality image only after a short timeout passes without selecting another image. Then, after downloading the image with high quality, show it only if it is still selected.

I don't know if these are best practices or anything, but it worked quite well .

+1
source

Source: https://habr.com/ru/post/946857/


All Articles