我有大约一百个简单的SVG图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们就会立即被检索出来。这在很大程度上起作用,但它有时会引起闪烁,我想消除这种闪烁。有没有办法在需要时预先加载这些图像,以便它们能够被缓存?我在这里看到了一些解决方案,但他们主要处理少量图像。有没有一种高音量预加载的首选方式?预加载SVG图像
谢谢!
我有大约一百个简单的SVG图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们就会立即被检索出来。这在很大程度上起作用,但它有时会引起闪烁,我想消除这种闪烁。有没有办法在需要时预先加载这些图像,以便它们能够被缓存?我在这里看到了一些解决方案,但他们主要处理少量图像。有没有一种高音量预加载的首选方式?预加载SVG图像
谢谢!
如果您拥有图片的所有网址,您可以开始使用网址尽快将它们缓存在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
和服务的情况下,一些“缺少“图像作为替换
可能使用jQuery预加载图像的副本(http://stackoverflow.com/questions/476679/preloading-images-with-jquery) – bvdb