I am currently working on implementing a basic lazy loading functionality for images. The idea is to process an array of images and remove each image from the array once it has been loaded.
Below is the code I have written:
const removeFromArray = (id) => {
const position = images.indexOf(id);
if (id.classList.contains(classes.loaded)) {
images.splice(id, 1);
}
}
const setHeight = (img, target) => {
const parentWidth = img.parentNode.offsetWidth;
const initw = target.width;
const inith = target.height;
return (parentWidth / initw) * inith;
}
const loadImage = (img) => {
const image = new Image();
img.classList.add(classes.loading);
image.src = img.getAttribute('data-lazy-img');
image.onload = function(e) {
const target = e.target || e.srcElement;
img.style.height = `${setHeight(img, target)}px`;
img.classList.add(classes.loaded);
img.classList.remove(classes.loading);
img.src = img.getAttribute('data-lazy-img');
removeFromArray(img);
}
}
The issue I am facing is that sometimes the incorrect image is removed from the array, especially when removing the later ones.
You can view my entire code here: http://codepen.io/tomekbuszewski/pen/LbRQxq?editors=0011
What steps should I take to address this problem?