2015-05-29 119 views
3

我有大约一百个简单的SVG图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们就会立即被检索出来。这在很大程度上起作用,但它有时会引起闪烁,我想消除这种闪烁。有没有办法在需要时预先加载这些图像,以便它们能够被缓存?我在这里看到了一些解决方案,但他们主要处理少量图像。有没有一种高音量预加载的首选方式?预加载SVG图像

谢谢!

+0

可能使用jQuery预加载图像的副本(http://stackoverflow.com/questions/476679/preloading-images-with-jquery) – bvdb

回答

4

如果您拥有图片的所有网址,您可以开始使用网址尽快将它们缓存在JS对象中,稍后在需要时从它们那里获取它们。

在您的页面中,您可能会在某处存储SVG图像列表,但最终您需要的仅仅是JS数组的URL字符串。

这里有一个简单的例子:

// 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的怪癖,但基本的解决方案应该工作。
+0

感谢您的非常详细的答案!一旦它们被缓存了,我仍然可以像以前那样对它们进行调用,它只是将它从缓存中提取出来,还是需要使用svgCache数组?对不起,我对此无知! – jldavis76

+0

我已经添加了一个函数来将图像追加到DOM,以及如何在'alldone'函数中调用它。 – MarcoL

+0

再次感谢!最后一个问题...你会在哪里推荐我放这个脚本?在头标签? – jldavis76