javascript图片预先加载

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
    
    </body>
    <script>
    var imgArr=["img/s1.png","img/s2.png","img/s3.png","img/s4.png","img/s5.png","img/s6.png","img/s7.png","img/s8.png",
            "img/s8.png","img/s10.png","img/s11.png","img/s12.png","img/s13.png","img/s14.png","img/s15.png","img/s16.png",
            "img/s17.png","img/s18.png","img/select.png"];
        preloadimages(imgArr).done(function(images){
            select()
        })
    function preloadimages(arr){   
    var newimages=[], loadedimages=0
    var postaction=function(){}  //此处增加了一个postaction函数
    var arr=(typeof arr!="object")? [arr] : arr
    function imageloadpost(){
        loadedimages++
        if (loadedimages==arr.length){
            postaction(newimages) //加载完成用我们调用postaction函数并将newimages数组做为参数传递进去
        }
    }
    for (var i=0; i<arr.length; i++){
        newimages[i]=new Image()
        newimages[i].src=arr[i]
        newimages[i].onload=function(){
            imageloadpost()
        }
        newimages[i].onerror=function(){
            imageloadpost()
        }
    }
    return { //此处返回一个空白对象的done方法
        done:function(f){
            postaction=f || postaction
        }
    }
}
    </script>
</html>

 

posted @ 2016-01-18 10:44  ZaneY  阅读(270)  评论(0编辑  收藏  举报