There are a number of possible solutions to this question. I'll list the common three below.
A CSS only solution, a javascript solution, and a HTML5 solution if you don't care about older browsers:
CSS
I would suggest moving the images into style tags and use media queries to show the appropriate image:
<style>
/* mobile first */
.img {
display:none;
}
/* tablet */
@media (min-width:600px) {
.img {
background:url('/path/to/image-tablet.png') no-repeat scroll 0 0 transparent;
}
}
/* desktop */
@media (min-width:1280px) {
.img {
background:url('/path/to/image-large.png') no-repeat scroll 0 0 transparent;
}
}
</style>
<div class="img"></div>
Assuming this is a dynamic webpage, you would include the css in the page withing style
tags instead of in a css file.
HTML5
If you are not bothered about complete browser coverage (canIuse), you could also use the new HTML5 picture
element:
<picture>
<source
media="(min-width: 1280px)"
srcset="/path/to/image-large.png">
<source
media="(min-width: 600px)"
srcset="/path/to/image-tablet.png">
<img src="/path/to/image-mobile.png" /> <!-- a 1x1 empty pixel -->
</picture>
In this example, mobile browsers and browsers that do not support it will load the img
tag. Other browsers will load the appropriate image for the media query.
If you like this solution but also want it to work on older browsers, there are JS scripts you can find that will implement the feature if the browser does not support it.
Javascript
This approach feels the most hacky to me, but that is just my opinion. It has a very large browser coverage, with IE supporting this method since 10.
Create an image tag without the src
attribute, and the image size versions as data
attributes:
<img data-tablet="/path/to/tablet.png" data-desktop="/path/to/large.png" />
<script>
var $el = jQuery('img');
if(window.matchMedia("(min-width: 600px)").matches) {
$el.attr('src', $el.data('tablet'));
}
if(window.matchMedia("(min-width: 1280px)").matches) {
$el.attr('src', $el.data('desktop'));
}
</script>
I've used jQuery to demonstrate, but the important part of this is the window.matchMedia
. This does a media-query like check and returns a boolean value.