Official way to ask jQuery wait for all images to load before executing something

前端 未结 10 2341
攒了一身酷
攒了一身酷 2020-11-22 00:04

In jQuery when you do this:

$(function() {
   alert(\"DOM is loaded, but images not necessarily all loaded\");
});

It waits for the DOM to

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 00:21

    My solution is similar to molokoloco. Written as jQuery function:

    $.fn.waitForImages = function (callback) {
        var $img = $('img', this),
            totalImg = $img.length;
    
        var waitImgLoad = function () {
            totalImg--;
            if (!totalImg) {
                callback();
            }
        };
    
        $img.each(function () {
            if (this.complete) { 
                waitImgLoad();
            }
        })
    
        $img.load(waitImgLoad)
            .error(waitImgLoad);
    };
    

    example:

提交回复
热议问题