Pregunta

I'm trying to preload images and as soon as they are fully loaded they shall be faded in smoothly (using JQuery). While loading a small loading animation is displayed. For this I tried to create an invisible image tag and let them load there. As soon as they have finished loading i tried to set the source of the original img-tag back to the original.

However I don't find my error for several hours now and have no clue. It seems that it ends up in an infinite loop and then creating the "preload-img-tags" again and again and again.

my HTML:

<img src="someimg.jpg" id="img2load" class="preload_img" style="max-width:400px; max-height:400px;">

my JS:

$(document).ready(function() {

var objs = document.getElementsByClassName("preload_img");

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

    objs[i].setAttribute("restoreImgPath", objs[i].src);

    //create div for preloading
    var img = document.createElement("img");
    img.setAttribute("src", objs[i].src);
    img.setAttribute("style", "position:absolute; top:0px; left:0px; display:none;");
    img.setAttribute("preloadForId", objs[i].id);
    img.setAttribute("id", "preload_" + objs[i].id);
    document.body.appendChild(img);

    //display loading gif
    objs[i].setAttribute("src", "loading.gif");

   //restore image [... not yet implemented ...]

}
});

Thanks in advance. I'm not very experienced in JS yet so please be patient with me 0:-)

¿Fue útil?

Solución

Well, this looks like the problem:

document.body.appendChild(img);

You keep adding new images. It looks like you are somehow copying over the class names, as well, so objs.length keeps getting bigger, and your loop is infinite. Do this instead:

var starting_length = objs.length;
for (var i = 0; i < starting_length; i++) {
    ....
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top