Preloading Images & [object HTMLImageElement]

情到浓时终转凉″ 提交于 2019-12-01 00:32:20

Just declare a counter and increment it as you go:

$(panel).each(function(){
        var loaded = 0; // <== The counter

    // Find Panel
        var panelId = $(this).attr('id');
        console.log('Loading ' + panelId);  

    // Find Images
        var images = $(this).find('img');
        var path = images.attr('src');
        console.log('Total of ' + images.length + ' Images');

    // Preload Images
        for( i= 0; i < images.length; i++ ) {

            images[i] = new Image();
            images[i].src = path;
            images[i].onload = function(){
                ++loaded;
                console.log('Loaded ' + loaded + ' of ' + images.length);
            };

        }

    // End

});

Don't use i, as at least one commenter suggested (and as I suggested before reading your code more carefully). i will always be images.length by the time the load callback is done.

Another change you need to make is to set the onload callback before setting src, so instead of:

// PROBLEM, sets up a race condition
images[i].src = path;
images[i].onload = function(){
    // ...
};

do this:

images[i].onload = function(){
    // ...
};
images[i].src = path;

JavaScript on web browsers is single-threaded (barring the use of web workers), but the web browser is not. It can easily check its cache and see that it has the image and run its code to trigger the load handlers between the line setting src and the line setting onload. It will queue up the handlers to be run the next time the JavaScript engine is available, but if your handler isn't there to get queued, it won't get queued, and you never get the load event callback.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!