首页 > 代码库 > 简单图片预加载

简单图片预加载

预加载是一项被广泛使用的技术。下面简单实现下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>

</head>
<body>
    <div id="outer"></div>

    <script>
        var imgArr = [img/1.jpg,img/2.jpg,img/3.jpg,img/4.jpg],
            outer = document.getElementById(outer),
            img = document.querySelectorAll(img),
            preload = function(arr){
                var i,
                    len = imgArr.length,//要加载的图片数量
                    loaded = 0,//已加载图片数量
                    newImg = [],//图片容器
                    end = function(){},
                    //加载完成后调用的函数
                    loadImg = function(){
                        loaded++;
                        alert(又加载完了一张图片!);
                        if(loaded === len){
                            end(newImg);
                        }
                };

                for(i=0; i<len; i++){
                    newImg[i] = new Image();
                    newImg[i].src = imgArr[i];
                    

                    newImg[i].onload = (function(i){
                        console.log(document.body.innerHTML);
                        loadImg();
                        console.log(a);
                        outer.appendChild(newImg[i]);
                    })(i)
                    // img[i].src = http://www.mamicode.com/imgArr[i];
                }

                return{
                    done: function(fn){
                        if(fn) end = fn;
                    }
                }
            };

        window.onload = function(){
            preload(imgArr).done(function(){
                alert(全部加载完);
            });
        }
        
    </script>
</body>
</html>

 

简单图片预加载