使用队列预加载图像

Preload images with queuing?

本文关键字:加载 图像 队列      更新时间:2023-09-26

我正在寻找的是一种方法来预加载并在队列中碰撞特定的图像。

这里是我到目前为止的地方:http://shivimpanim.org/testsite/imageloader.html

您可以看到它有图像预加载,但据我所知没有队列管理(或者如果新写入DOM,浏览器是否会智能地在队列中增加请求的图像?)

换句话说-可能是image10自然地接近预加载队列的末尾…然而,它可能是用户在开始时徘徊的地方。因此image10应该被放到队列的顶部并立即加载。完成后,队列应该从它停止的地方继续加载。

谢谢!

EDIT:我现在已经更新了代码,以便预加载工作…主要的"陷阱"是图像必须添加到DOM中,以便在Mac上的firefox中触发onLoad,并且我需要沿着路径跟踪原始索引(以匹配标题等)

似乎工作…但奇怪的是,第二个项目的顺序很奇怪(在自动模式下,它在加载项目#2之前加载项目#3)。

但总而言之-它自动加载大多数以正确的顺序2项,并且当用户悬停在一个链接上时,它会将该项目放入队列,然后在加载时显示它:)

我还没有进行广泛的测试-但在firebug中,事情看起来有点正常:)

像这样(未经测试):

function loader( images, n_parallel ){
    this.queue   = images.slice( 0 );
    this.loading = [];
    for( var i=0; i<n_parallel; i++ ) this.dequeue();
}
loader.prototype.dequeue = function(){
    if( !this.loading.length ){ return; }
    var img = new Image(),
       self = this;
    img.src = this.queue.unshift();
    if(img.width){
        self.dequeue();
    }else{
        img.onload = function(){
            self.dequeue();
        }
    }
}
loader.prototype.promote = function( src ){
    for(var i=0, l=this.queue.length; i<l; i++){
        if(this.queue[i] == src){
            this.queue.unshift( this.queue.splice(i, 1)[0] );
            break;
        }
    }
}

var imgs = new loader( ['foo.jpg', 'bar.jpg', 'foobar.jpg', ...], 2 );
...
imgs.promote( 'some_img.jpg' );

为了使其工作,您也不能在页面加载时将所有图像添加到dom中。您需要按需添加它们。