Why does this attempt to preload images using jQuery not work?

Current I have this code:

var imgCount = 36;
var container = $('#3D-spin');

var loaded = 0;
function onLoad()
{
    alert(loaded);
    loaded++;
    if(loaded >= imgCount)
    {
        alert('yay');
    }
}

for(var i = imgCount-1; i >= 0; i--)
{
    container.prepend(
        $('<img>')
            .one('load', onLoad)
            .attr('alt', 'View from '+(i*360/imgCount)+'\u00B0')
            .attr('src', '/images/3d-spin/robot ('+i+').jpg')
    );
}

However, this behaves VERY weird. Usually I do not receive warning boxes. However, if I open developer tools and pause script execution, I get one warning that says 0. There nothign like the good old heisenbug!

An example can be found here . The script itself is called style.js, and it is clear that the images are uploaded.

Am I doing something stupid or is jQuery playing?

+3
source share
1 answer

, , onload . , , complete:

container.prepend(
    $('<img>')
        .one('load', onLoad)
        .attr('alt', 'View from '+(i*360/imgCount)+'\u00B0')
        .attr('src', '/images/3d-spin/robot ('+i+').jpg')
        .each(function() { if(this.complete) $(this).trigger("load"); }
    );
+4

Source: https://habr.com/ru/post/1750490/


All Articles