Not working with only srcset
ashehzadgec opened this issue · comments
Hi there
I have a scenario where I have to use only srcset for images. The problem is, in this way it does not wait for the images to load and run the callback function. I did change the following line from the . js file as follows:
`// original code from js file
this.proxyImage.src = this.img.src;
// I changed it as for srcset workout
this.proxyImage.src = this.img.srcset;`
In this way it works like I want but it is making the double request for each image and throwing the error for 2nd img request.
How this can be fixed.
Regards,
Shehzad Asif
There needs to be some sort of check for when img.src
is empty, and to try to fallback to img.currentSrc
where only srcsets are used. Should be an easy PR The toolchain is pretty out of date for this repo and it might take some work to get it to build again.
Here's a set of functions I wrote to handle this myself. If anyone else might benefit from this go ahead:
function determineImageSource(elm) {
if (elm.src) return elm.src;
if (elm.currentSrc) return elm.currentSrc;
if (elm.style.backgroundImage) {
const pattern = /\burl\s*\(\s*["']?([^"'\r\n\)\(]+)["']?\s*\)/
match = elm.style.backgroundImage.match(pattern);
try {
return match[1]
}
catch {
return null
}
}
return null;
}
function isImageLoaded(elm) {
return new Promise(function(resolve, reject) {
var src = determineImageSource(elm);
if (src === null) return resolve();
var img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = function() {
resolve(img);
};
img.src = src;
})
}
function afterImagesLoad(parent, callback) {
var container = document.querySelector(parent);
if (container === null) throw Error('No parent for allImagesLoaded');
var imgElms = Array.from(container.querySelectorAll('img'));
var bgImages = Array.from(
container.querySelectorAll('[style*="background-image"]')
);
var imgs = imgElms.concat(bgImages);
var promises = imgs.map(isImageLoaded);
Promise.all(promises).then(callback)
}
imagesLoaded v5 has been released with better support for srcset
. Please upgrade and report back if you still run into issues.