javascript – 如何使用预加载器和多个图像显示加载状态?
作者:互联网
我正在构建一个包含几百个图像的幻灯片,并希望构建一个漂亮的加载栏,因此我们的想法是使用JavaScript预加载图像,然后初始化UI的其余部分.
预加载图像不是问题,而是让浏览器在加载时更新状态.我尝试过一些东西,但浏览器只会在显示完成后再重新显示.
我甚至尝试过this question的脚本,但是得到了相同的结果.
这是我到目前为止所得到的(imgList是一个文件名数组.我使用的是Prototype.)
var imageBuf = []
var loadCount = 0
$('loadStatus').update("0/"+imgList.length)
function init() {
imgList.each(function(element){
imageBuf[element] = new Image()
//imageBuf[element].onload = window.setTimeout("count()",0) // gives "not implemented" error in IE
imageBuf[element].onload = function(){count()}
imageBuf[element].src = "thumbs/"+element
})
}
function count() {
loadCount++
$('loadStatus').update(loadCount+"/"+imgList.length)
}
init()
解决方法:
尝试使用my answer to this question中的功能:
function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {
var itemIndex = 0;
(function() {
var remainingDataLength = (data.length - itemIndex);
var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;
if(itemIndex < data.length) {
while(currentChunkSize--) {
workerCallback(data[itemIndex++]);
}
setTimeout(arguments.callee, timeout);
} else if(completionCallback) {
completionCallback();
}
})();
}
// here we are using the above function to take
// a short break every time we load an image
function init() {
incrementallyProcess(function(element) {
imageBuf[element] = new Image();
imageBuf[element].onload = function(){count()};
imageBuf[element].src = "thumbs/"+element;
}, imgList, 1, 250, function() {
alert("done loading");
});
}
您可能希望修改块大小参数以及超时的长度,以使其行为与您希望的一样.我不是100%确定这对你有用,但值得一试……
标签:html,javascript,prototypejs 来源: https://codeday.me/bug/20191005/1856133.html