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?
2 Answers 2
You can bind the variable on your callback function:
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 (x) {
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded', 'true');
//where x is i value from for loop
}).bind(img, i);
img.src = imgs[i].getAttribute('data-src');
}
}
7 Comments
Call the function when the page has initialized, once, and let it be done.
Instead of calling onload on your images 250+ times (slowing down your page, as per your comment on Adam's answer, which is the opposite of what you want), maybe see what the tutorial has in store for you.
Re-inventing the wheel, but following this tutorial gives you a simple and straight-forward way to do it https://varvy.com/pagespeed/defer-images.html (and it looks like your code might be derived from it)
Hope this helps
img.onload = (function(x) { return function() { imgs[x].src = imgs[x].getAttribute('data-src'); imgs[x].setAttribute('srcLoaded', 'true'); //where x is i value from for loop } })(i);