0

我有一个代码,它依赖于首先加载的大图像数组,所以我试图做这样的事情:

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 循环。

4

1 回答 1

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;
}
于 2012-09-30T01:04:31.297 回答