Test if all images are loaded

前端 未结 3 942
难免孤独
难免孤独 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:16

    This is why closures were made! Your loop runs almost instantly, and it ends long before the first image is loaded. So i==imgCount right away, "skipping" all other values. Closures can avoid this and affect each value of i to a distinct image.

    However in your case, I would indeed add a "loaded" attribute to each image.

    // Construct your image array
    for (var i = 0; i < imgCount; i++) {
        imgArr[i] = new Image();
        imgArr[i].src='img'+i+'.png';
    }
    
    //Then iterate over the array, adding a 'loaded' attribute when it occurs
    imgArr.each(function(){
        $(this).onload(function() {
            $(this).attr('loaded','true');
        });
    }
    

提交回复
热议问题