Preload images with queuing?
What I'm looking for is a way to preload and bump a specific image up in the queue.
Here is where I'm at so far: http://shivimpanim.org/testsite/imageloader.html
You can see it has image preloading, but there is no queue management as far as I can tell (or does the browser intelligently bump up the requested image in the queue if it's newly written to the DOM?)
In other words- it might be that naturally image10 is towards开发者_如何学JAVA the end of the preload queue... yet it might be where the user hovers over right at the beginning. So image10 should be bumped to the top of the queue and immediately loaded. When finished, the queue should continue loading from where it left off.
Thanks!
EDIT: I've now updated the code so that preloading works... the main "gotchas" were that the image must be added to the DOM for onLoad to trigger in firefox on Mac, and my specific need to keep track of the original index along the route (to match title, etc.)
Seems to work.. but strangely, the order of the second item is weird (it loads item #3 before item #2 in auto-mode).
But all in all- it auto-loads mostly in the correct order 2 items at a time, and when the user hovers over a link it bumps that item into the queue and then shows it upon load :)
I haven't tested extensively- but in firebug things look somewhat normal :)
Something like this (untested):
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' );
In order for this to work, you can't also add all of the images to the dom on page load. You need to add them on-demand.
精彩评论