【发布时间】:2015-08-12 17:33:43
【问题描述】:
我有大约一百个简单的 SVG 图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们会立即被检索。这在大多数情况下是有效的,但它有时会导致闪烁,我想消除它。有没有办法在需要它们之前预加载这些图像,以便它们被缓存?我在这里看到了一些解决方案,但它们主要处理少量图像。有没有首选的方式来进行大容量预加载?
谢谢!
【问题讨论】:
标签: javascript php html css svg
我有大约一百个简单的 SVG 图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们会立即被检索。这在大多数情况下是有效的,但它有时会导致闪烁,我想消除它。有没有办法在需要它们之前预加载这些图像,以便它们被缓存?我在这里看到了一些解决方案,但它们主要处理少量图像。有没有首选的方式来进行大容量预加载?
谢谢!
【问题讨论】:
标签: javascript php html css svg
如果你有图片的所有 URL,你可以尽快开始使用 url 将它们缓存在 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 并提供一些“丢失”图像作为替换的情况【讨论】:
alldone 函数中调用它。
这是一个 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');
}
【讨论】: