Test if all images are loaded

前端 未结 3 895
难免孤独
难免孤独 2021-01-19 00:35

Here is my attempt at the ability to test if all images are loaded:

for (var i = 0; i < imgCount; i ++) {
    loadArr[i] = false
    imgArr[i] = new Image         


        
3条回答
  •  抹茶落季
    2021-01-19 01:34

    You need to define the onload function using a closure:

    for (var i = 0; i < imgCount; i ++) {
        loadArr[i] = false
        imgArr[i] = new Image()
        imgArr[i].src='img'+i+'.png'
        imgArr[i].onload = (function(i){
            return function(){ loadArr[i] = true }
        })(i);
    }
    

    Here's a jsFiddle which demonstrates this working in a similar scenario.

    Also, note that the solution you've currently selected as the answer doesn't actually work:

    imgArr[i].onload = (function() {
            loadArr[i] = true;
        })();
    

    This function is evaluated immediately. This means that in the loop, each element of the loadArr is set to true as is the onload event. That code is functionally identical to:

    imgArr[i].onload = loadArr[i] = true;
    

提交回复
热议问题