I wanted to implement the responsive images using srcset, as described here, so the image src that the user loads is the most similar to his resolution.
The thing is that I made this test and it doesn't respond to viewport changes,
<img src="https://lorempixel.com/400/200/sports/"
alt=""
sizes="(min-width:1420px) 610px,
(min-width:1320px) 500px,
(min-width:1000px) 430px,
(min-width:620px) 280px,
280px"
srcset="https://lorempixel.com/620/200/sports/ 280w,
https://lorempixel.com/1000/300/animals/ 430w,
https://lorempixel.com/1320/400/cats/ 610w,
https://lorempixel.com/1420/500/abstract/ 1000w,
https://lorempixel.com/1600/600/fashion/ 1220w" />
jsfiddle: http://jsfiddle.net/ad857m1r/9/
Any idea what I'm missing?
The srcset
attribute is interpreted by the browser at first load, then the loaded image is stored in cache
and the browser might not load any other image until you clear the cache
and reload the page.
If you want that the srcset
is reinterpreted on each resize
event of the page, you need to update it adding a random variable at the end of each url
, then the browser will reload the correct one for that screen size.
I've added a delay to this process to reduce the number of times that it is executed. You'll notice that this practice forces the browser to download the correct image at each resize and this is bad for bandwidth. I do not recommend the use of this technique, let the browser decides which image it uses on each situation. I think that viewport resize is not a common situation in an everyday environment. Maybe is better for your purposes the use of picture element (using some approach to making it compatible with old browsers) as @KrisD said.
var img = document.getElementById("myImage");
var srcset = img.getAttribute("srcset");
var delay;
window.onresize = function() {
clearTimeout(delay);
delay = setTimeout(refreshImage, 500);
}
function refreshImage() {
var reg = /([^\s]+)\s(.+)/g;
var random = Math.floor(Math.random() * 999999);
img.setAttribute("srcset", srcset.replace(reg, "$1?r=" + random + " $2"));
}
jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With