img not responding to srcset specified dimensions
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