我想在javascript中预加载一组图像并暂停,直到它们都被加载

时间:2012-09-30 00:56:19

标签: javascript while-loop preload

我的代码依赖于首先加载的大型图像数组,因此我尝试做这样的事情:

var loading = 0;
    var i = 0;
    var imgs = [];
    var background = [
        'bg1-1', 'bg1-2', 'bg1-3', 'bg1-4',
        'bg2-1', 'bg2-2', 'bg2-3', 'bg2-4',
        'bg3-1', 'bg3-2', 'bg3-3', 'bg3-4',
        'bg4-1', 'bg4-2', 'bg4-3', 'bg4-4'
    ];

    for (i = 0; i < background.length; i++) {
        imgs[i] = document.getElementById(background[i]);
        imgs[i].onload = function() {
            loading++;
        }
    }

    while (loading < 16) {  }

    alert('images loaded!'); //I need to ensure images are fully loaded here.

所以,它只是挂起,永远不会退出while循环。

1 个答案:

答案 0 :(得分:1)

将条件和警报放入回调中。

var loading = 0;

for (i = 0; i < background.length; i++) {
    imgs[i] = document.getElementById(background[i]);
    imgs[i].onload = function() {
        loading++;
        if (loading >= background.length)
            alert("all done");
    }
}

实际上重用该功能会更好。

var loading = 0;

function imgHandler() {
    loading++;
    if (loading >= background.length)
        alert("all done");
}

for (i = 0; i < background.length; i++) {
    imgs[i] = document.getElementById(background[i]);
    imgs[i].onload = imgHandler;
}