预加载SVG图像

时间:2015-05-29 18:22:49

标签: javascript php html css svg

我有大约一百个简单的SVG图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,立即检索它们。这在很大程度上起作用,但它确实会导致闪烁,我想消除。有没有办法在需要之前预先加载这些图像,以便它们被缓存?我在这里看到了一些解决方案,但它们主要处理少量图像。是否有一种优先的方法来进行大容量预载?

谢谢!

2 个答案:

答案 0 :(得分:4)

如果您拥有图像的所有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);
}

注意

  • 还要考虑加载图片时出现错误的情况,因此也请回调img.onerror并提供一些“缺失”图片作为替换
  • 这里还有一些需要考虑的事情,比如一些带有SVG的浏览器怪癖,但基本的解决方案应该可行。

答案 1 :(得分:0)

这是一个CSS解决方案:

.my-class{
    // this will put the rollover image behind and act as a preloader
    background-image:url('../images/svg/btn.svg'), url('../images/svg/btn-over.svg');
}

.my-class:over{
    background-image:url('../images/svg/btn_over.svg');
}