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

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

    This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.

    var counter = 0;
    var size = $('img').length;
    
    $("img").load(function() { // many or just one image(w) inside body or any other container
        counter += 1;
        counter === size && $('body').css('background-color', '#fffaaa'); // any action
    }).each(function() {
      this.complete && $(this).load();        
    });
    

提交回复
热议问题