预加载SVG图像

jld*_*s76 5 html javascript css php svg

我大约有一百个简单的SVG图像,它们存储在大约五个不同的图像文件夹中。当前,当需要显示它们时,将立即检索它们。在大多数情况下,这是可行的,但有时会引起闪烁,我想消除这种闪烁。有没有一种方法可以在需要它们之前预加载这些图像,以便对其进行缓存?我在这里看到了一些解决方案,但它们主要处理少量图像。有进行大容量预紧的首选方法吗?

谢谢!

Mar*_*coL 5

如果您拥有图像的所有URL,则可以开始使用url在JS对象中尽快将其缓存,然后在需要时从那里获取它们。

在页面中,您可能会将SVG图像列表存储在某个位置,但是最后所需的只是URL字符串的JS数组。

这是一个简单的示例:

// assuming you've gotten the urls from somewhere and put them in a JS array
var urls = ['url_image_1.svg', 'url_image_2.svg', ... ];

var svgCache = {};

function loaded(){
  // just increment the counter if there are still images pending...
  if(counter++ >= total){
    // this function will be called when everything is loaded
    // e.g. you can set a flag to say "I've got all the images now"
    alldone();
  }
}

var counter = 0;
var total = urls.length;

// This will load the images in parallel:
// In most browsers you can have between 4 to 6 parallel requests
// IE7/8 can only do 2 requests in parallel per time
for( var i=0; i < total; i++){
  var img = new Image();
  // When done call the function "loaded"
  img.onload = loaded;
  // cache it
  svgCache[urls[i]] = img;
  img.src = urls[i];
}

function alldone(){
  // from this point on you can use the cache to serve the images
  ...
  // say you want to load only the first image
  showImage('url_image_1.svg', 'imageDivId');
}

// basically every time you want to load a different image just use this function
function showImage(url, id){
  // get the image referenced by the given url
  var cached = svgCache[url];
  // and append it to the element with the given id
  document.getElementById(id).appendChild(cached);
}
Run Code Online (Sandbox Code Playgroud)

注意事项

  • 还请考虑加载图像时出现错误的情况,因此也要添加回调img.onerror,以防某些“丢失”的图像被替换
  • 这里还有更多注意事项,例如一些带有SVG的浏览器怪癖,但基本解决方案应该可以工作。