javascript - 掌握预加载图像

标签 javascript jquery preloading

我在使用 JS 预加载图像时遇到一些问题。我有一个 fiddle ,我试图创建三个图像对象并一一加载它们,但是我只得到一张图像?任何帮助表示赞赏。

http://jsfiddle.net/gq1oqnxb/1/

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

        var images = new Array();

    images[0] = 'http://hdcomputerwallpaper.com/wp-content/uploads/2013/12/Puppy-images.jpg';
    images[1] = 'http://hdcomputerwallpaper.com/wp-content/uploads/2013/12/Puppy-images.jpg';
    images[2] = 'http://wallfc.com/wp-content/uploads/2014/09/Little-Birds.jpg';
    var i = 0;      

    while(i < images.length){

    var image = new Image(50,50);
    image.src = images[i];
    image.onload = function(){

                        $('body').append(image);
                        i++;
                                }
    i++
    }



    });

</script>
</head>

<body>

</body>

最佳答案

Fiddle Demo

imageLoader(0); //call the function with first image to load `0` as index starts from `0`
function imageLoader(i) { //function to load images one by one and pass the array index
    var image = new Image(50, 50); //create a new image
    image.src = images[i]; //set src of the image from images array
    image.onload = function () { //on image load 
        $('body').append(image); //append to the the body
        if (++i >= images.length) return; //increment i check the length of images is exceeded than return
        imageLoader(i); //more images are present in array then call the function again 
    }
}

关于javascript - 掌握预加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26194495/

相关文章:

jquery - 火狐浏览器中如何处理 "image corrupt or truncated"

php - 在请求播放之前,如何阻止嵌入的声音片段下载到浏览器缓存中?

ios - 应用程序/后端架构 : How do Snapchat stories load so fast?

javascript - 如何在 Javascript 中打开下载对话框?

javascript - 区分平板电脑/智能手机和触摸屏电脑

javascript - 我想在 JavaDoc 中添加 JavaScript

javascript - 如何根据出现顺序更改多个图像的百分比宽度?

javascript - 如何在谷歌图表中刷新页面后停止 x 轴文本相互重叠

css - 如何仅使用CSS(不使用JS)预加载图像?

javascript - 如何一次缩小多个 HTML/CSS 文件?