Fire an event after preloading images

前端 未结 10 1915
北海茫月
北海茫月 2020-12-25 15:25

This is the code I use to preload images, I\'m not sure if it\'s the best one. My question is, how can I fire and event, for an example alert(); dialog after is has finished

10条回答
  •  攒了一身酷
    2020-12-25 15:49

    //Here is a pre-jquery method, but jquery is bound to be simpler to write.

    function loadAlbum(A, cb, err, limit){
        // A is an array of image urls;
        //cb is a callback function (optional);
        //err is an error handler (optional);
        // limit is an (optional) integer time limit in milliseconds
    
        if(limit) limit= new Date().getTime()+limit;
        var album= [], L= A.length, tem, url;
    
        while(A.length){
            tem= new Image;
            url= A.shift();
            tem.onload= function(){
                album.push(this.src);
            }
            tem.onerror= function(){
                if(typeof er== 'function') album.push(er(this.src));
                else album.push('');
            }
            tem.src= url;
    
            // attend to images in cache (may not fire an onload in some browsers):
            if(tem.complete && tem.width> 0){
                album.push(tem.src);
                tem.onload= '';
            }
        }
        // check the length of the loaded array of images at intervals:
        if(typeof cb== 'function'){
            window.tryAlbum= setInterval(function(){
                if(limit && limit-new Date().getTime()<0) L= album.length;
                if(L== album.length){
                    clearInterval(tryAlbum);
                    tryAlbum= null;
                    return cb(album);
                }
            },
            100);
        }
        return album;
    }
    

提交回复
热议问题