Javascript Image After Loader

So, I am writing javascript that replaces the default image, which fills the space for numerous images on my web page. Thus, the page loads much faster. (the script is displayed with the body loading), all images by default have the same class, and their identifier is equal to their file name.

function imgPostLoad(totalpics, placeholder) {
    var img = document.createElement('img');
    for (var i = 0; i < totalpics; i++) {
        var picture = document.getElementsByClassName(placeholder)[i];
        img.onload = function (evt) {
            picture.src = this.src;
            picture.width = this.width;
            picture.height = this.height;
        }
        img.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}

It works, but only for the last last image in the array. The remaining images remain unchanged. What is wrong with him?

+4
source share
4 answers

You can just do:

function imgPostLoad(totalpics, placeholder) {
    for (var i = 0; i < totalpics; i++) {
        var picture = document.getElementsByClassName(placeholder)[i];
        picture.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}

, , img picture .

+1
function imgPostLoad(placeholder) {
    var allPictures = document.getElementsByClassName(placeholder);
    for (var i = 0; i < allPictures.length; i++) {
        var picture = allPictures[i];
        picture.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}
0

Actually, it would be easier to write it like this.

function imgPostLoad() {

     var placeHolders = document.body.querySelectorAll('.placeholder');

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

        placeHolders[i].src = "/img/" + placeHolders[i].getAttribute("id") + ".jpg";
    }
}
0
source

create an image element in a for loop like this

function imgPostLoad(totalpics, placeholder){
    for (var i = 0; i < totalpics; i++){
        var img = document.createElement('img');
        var picture = document.getElementsByClassName(placeholder)[i];
        img.onload = function (evt) {
            picture.src=this.src;
            picture.width=this.width;
            picture.height=this.height;
        }
        img.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}
-1
source

All Articles