I am trying to implement lazy loading on my personal project. I have been able to make it work on my homepage, or my gallery page, but never both.
I believe the issue is that "lowResImage" is not updating it's path to the next item in the array.
I apologize if this code is poorly written, I am just beginning to learn, and I've moved things around a lot trying to find a solution.
// SET RES-IMAGE-REPLACEMENT, AND RUN LAZYLOADERSETUP ON EACH IMAGE
resImageReplacements = document.getElementsByClassName('res-image-replacement');
for (let i = 0; i < resImageReplacements.length; i++) {
lazyLoaderSetup(resImageReplacements[i], i);
}
function lazyLoaderSetup(i) {
highResImage = document.createElement("IMG");
lowResImage = document.getElementsByClassName('picturesToBeSwapped')[i];
resReplacement = document.getElementsByClassName("res-image-replacement")[i];
// SET HIGH RES IMAGE UP WITH CLASS, ID, AND HIGH RES SOURCE
highResImage.setAttribute("class", "mainBackground");
highResImage.setAttribute("id", "mainBackground");
highResImage.setAttribute('src', lowResImage.getAttribute("high-res-src"));
// IF THE LOW RES IMAGE CLASS EXISTS, ADD THE LOAD LISTENER WHICH WILL RUN REMOVEAPPEND FUNCTION
if (resReplacement.contains(lowResImage)) {
highResImage.addEventListener('load', removeAppend);
}
}
// REMOVE THE LOW RES ELEMENT, ADD THE HIGH RES ELEMENT, REMOVE LISTENER
function removeAppend() {
resReplacement.removeChild(lowResImage);
resReplacement.appendChild(highResImage);
highResImage.removeEventListener('load', removeAppend);
}
I finally got the Lazy Loader to function correctly. Setting lowResImage to always be the first element in the picturesToBeSwapped array fixed my issue. Here is my updated code, hopefully it can be helpful to someone in the future.
// SET RES-IMAGE-REPLACEMENT, AND RUN LAZYLOADERSETUP ON EACH IMAGE
resImageReplacements = document.getElementsByClassName('res-image-replacement');
for (let i = 0; i < resImageReplacements.length; i++) {
lazyLoaderSetup(i);
}
function lazyLoaderSetup( i) {
highResImage = document.createElement("IMG");
lowResImage = document.getElementsByClassName('picturesToBeSwapped')[0];
resReplacement = document.getElementsByClassName("res-image-replacement")[i];
// SET HIGH RES IMAGE UP WITH CLASS, ID, AND HIGH RES SOURCE
highResImage.setAttribute("class", "mainBackground");
highResImage.setAttribute('src', lowResImage.getAttribute("high-res-src"));
// IF THE LOW RES IMAGE CLASS EXISTS, ADD THE LOAD LISTENER WHICH WILL RUN REMOVEAPPEND FUNCTION
if (resReplacement.contains(lowResImage)) {
highResImage.addEventListener('load', removeAppend);
}
}
// REMOVE THE LOW RES ELEMENT, ADD THE HIGH RES ELEMENT, REMOVE LISTENER
function removeAppend() {
resReplacement.removeChild(lowResImage);
resReplacement.appendChild(highResImage);
highResImage.removeEventListener('load', removeAppend());
}