I want to use image.onload in $.when function

后端 未结 1 1940
北荒
北荒 2021-01-27 06:00

I am loading images dynamic inside loop.I have some requirement such that in following code when I am loading image then and then only alert fire and when alert 1 fires then

相关标签:
1条回答
  • 2021-01-27 06:54

    To convert image loading into a (jQuery) promise, use:

    function imageLoad(url) {
        return $.Deferred(function(def) {
            var img = new Image();
            img.onload = function() {
                def.resolve(img);
            };
            img.src = url;
        });
    }
    

    You can then create an array of Promises for your images:

    var promises = imggg.map(imageLoad);
    

    and then pass that to $.when:

    $.when.apply($, promises).then(function() {
         console.log("all images loaded");
    });
    
    0 讨论(0)
提交回复
热议问题