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

前端 未结 10 2484
攒了一身酷
攒了一身酷 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:27

    With jQuery i come with this...

    $(function() {
        var $img = $('img'),
            totalImg = $img.length;
    
        var waitImgDone = function() {
            totalImg--;
            if (!totalImg) alert("Images loaded!");
        };
    
        $('img').each(function() {
            $(this)
                .load(waitImgDone)
                .error(waitImgDone);
        });
    });
    

    Demo : http://jsfiddle.net/molokoloco/NWjDb/

提交回复
热议问题