Hide images until they're loaded

2020-02-11 13:11发布

问题:

I got a jQuery script which is dinamically appending data to the "holder" at some timeinterval. The data looks like this:

<div class="item-box etc etc"> <img src="data.png"> </div>

and I'm loading like 50 images at once, my goal is to make them fadeIn, when each image is loaded.

I've tried the following:

parentDiv.on("load", "img", function() {
    $(this).parent().fadeIn(500);
});

Fiddle: http://jsfiddle.net/3ESUm/2/

but seems that on method doesn't have load or ready methods. I ran out of ideas.

回答1:

just set the onload property when you add the image.

var img = new Image();
img.src = "some url"
img.onload=function(){$(img).fadeIn(500);}
document.getElementByID('parent').appendChild(img);

see working example here



回答2:

You can add your images in first-loaded-first displayed order like this:

Demo: http://jsfiddle.net/m1erickson/7w6cb/

var imageURLs=[];
var imgs=[];
imageURLs.push("house100x100.png");
imageURLs.push("house32x32.png");
imageURLs.push("house16x16.png");

for(var i=0;i<imageURLs.length;i++){

    imgs.push(document.createElement("img"));
    imgs[i].onload=function(){
        var id=this.myId;
        this.id=id;           
        document.body.appendChild(this);
        $("#"+id).hide().fadeIn(1500);
    }
    imgs[i].myId=i;
    imgs[i].src=imageURLs[i];
}