Workaround/Idea: Preloading images with srcset attributes (chrome)
See original GitHub issueHi, I’m working on a mobile app and was searching for a solution to preload the “current” image when an image has the srcset attribute (for calculating it’s container height). I had many issues on chrome/win and resolved them by using the img property ‘currentSrc’.
Because there was no event, when currentSrc has been set by chrome (I was testing many timeout values), I choose following approach:
function waitForComputedSrcset (images, $dfd) {
$dfd = $dfd || $.Deferred();
var computed = 0,
length = images.length;
for (var i = 0; i < length; i++) {
if (images[i].hasOwnProperty('currentSrc') && !! !images[i].currentSrc) {
window.setTimeout(this.waitForComputedSrcset.bind(this, images, $dfd), 100);
return $dfd;
}
computed++;
}
return (length === computed) ? $dfd.resolve(images) : $dfd;
}
When all images are “computed” by chrome I set all src properties of the resolved images to var length = images.length; for (var i = 0; i < length; i++) { if (images[i].hasOwnProperty(‘currentSrc’) && !! !images[i].currentSrc) { images.src = images[i].currentSrc; } }
I’m not sure if this is a solution to the specs, but so I’ve got it working and imagesloaded doesn’t load the wrong images initially. Imo/Hopefully only browsers, which are supporting the srcset attribute are setting img.currentSrc.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:2
- Comments:8 (1 by maintainers)
Top GitHub Comments
Hi,
I did not find a solution with imagesLoaded for my issue than I wrote a simple function with some jQuery improvemens. That works for me now without imagesLoaded library:
My Pen: http://codepen.io/hayatbiralem/pen/jbjLZe?editors=001 Original Pen: http://codepen.io/desandro/pen/bIFyl
The workaround from @rs3d is doing the trick now for me. It’s loading fine in Chrome 40 (PC)