Reputation: 10219
I need a banner to display at full width across many screen sizes. To accomplish this, I have 4 versions of the banner image.
I'm using the srcset
attribute.
<img
src="/images/interface/banner-long.jpg"
srcset="/images/interface/[email protected] 2880w,
/images/interface/banner-long.jpg 1440w,
/images/interface/[email protected] 1439w,
/images/interface/banner-short.jpg 720w">
However, if I start with a wide browser so that the long version loads, and then shrink the width of the browser, the short version never loads because the long version is cached. The browser (Chrome) figures it's already download a higher-resolution version, so it doesn't bother loading the smaller version. However, the whole point of having a smaller version is that the aspect ratio is more suitable for mobile devices (i.e. the aspect ratio is smaller). I'd like to force the smaller image asset to load
Is there any way to do this?
Upvotes: 3
Views: 1825
Reputation: 14134
This is not the way you should do this. What you want is called artdirection and you need to use the picture element for this. There you can use source elements with media attributes.
<picture>
<source
srcset="/images/interface/[email protected] 2880w,
/images/interface/banner-long.jpg 1440w"
media="(min-width: 800px)"
/>
<img srcset="/images/interface/[email protected] 1439w,
/images/interface/banner-short.jpg 720w" />
</picture>
Upvotes: 5
Reputation: 3330
If you're building this HTML dynamically, just append ?t=<current unix timestamp>
to the URL of every image. That way, the browser will have to load them from the server every time because the URL will always be different.
Alternatively, you could configure your web server to send "don't cache" headers when it sends those images (but this is probably more difficult and overly complicated).
I do question the use of srcsets for this purpose. It might work, but I'm not sure srcset is the best tool for the job, or that srcsets are intended to be used in this way. If you're switching the actual image, it seems like that ought to be done by two different image tags, each with its own srcset (which you can show/hide at different resolutions), or with some JS solution of some kind.
Upvotes: 1