This is not a duplicate question. I have been working on loading images after the complete page load. I want to pass variable i
value to the onload
function of img but somehow that's not working.
var imgs = document.getElementsByTagName('img');
var totalImages = imgs.length;
for(var i=0; i<totalImages; i++)
{
if(imgs[i].hasAttribute('data-src'))
{
var img = new Image();
img.onload = function()
{
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
};
img.src = imgs[i].getAttribute('data-src');
}
}
I tried following onload function
img.onload = (function(x)
{
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
})(i);
but in this way, I saw that function is executed immediately even the image is not completely loaded may be because this is somehow working as anonymous function.
I also tried by setting attribute to my img
object and getting its value inside function like this
img.setAttribute('idi',i);
img.onload = function()
{
var x = img.getAttribute('idi');
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
};
but that's not working as well. How can I pass variable i
value to my onload function?