Some people use the argument that you can’t have responsive images with responsive CSS, so it doesn’t work well if you have an image heavy site. This is just silly. I’ll show you two (well, one and a half) easy ways to handle multi resolution versions of images in the frontend.
First some HTML. Notice the use of “data-” to hold image URLs.
<figure> <img class="responsive" data-highres="http://placekitten.com/g/1000/500" data-mediumres="http://placekitten.com/g/800/400" data-lowres="http://placekitten.com/g/320/160" /> </figure>
Slap on some simple JS to switch the image tags’ src attribute and you’re good to go.
$(document).ready(function(){ resizeImages($(window).width()); addEvent(window, "resize", function(){ resizeImages($(window).width()); }); }); function resizeImages(viewPortX){ if (viewPortX <= 320) { var imgres = 'lowres'; } else if (viewPortX <= 500) { imgres = 'mediumres'; } else { imgres = 'highres'; } $('img.responsive').each(function(){ var theimg = $(this); var imgurl = theimg.data(imgres); theimg.attr('src',imgurl); }); $('#width').text('$(window).width(): ' + viewPortX); } function addEvent(elem, type, eventHandle){ if (elem == null || elem == undefined) return; if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } }
You can view this example here. Resize the result view and watch the magic. This method works even if your images are on another server than your JavaScript, since the JavaScript isn’t doing the requests.
It’s easy to modify the first script to make sure that the image source is updated only after the request for an image is complete and successful.
function resizeImages(viewPortX){ if (viewPortX <= 320) { var imgres = 'lowres'; } else if (viewPortX <= 500) { imgres = 'mediumres'; } else { imgres = 'highres'; } $('img.responsive').each(function(){ var theimg = $(this); var imgurl = theimg.data(imgres); if (imgurl && theimg.data('requesting') != true && theimg.attr('src') != imgurl) { $.ajax({ type: 'GET', url: imgurl, beforeSend: function(){ theimg.data('requesting',true); }, success: function(data, textStatus, jqXHR){ theimg.attr('src',imgurl); }, complete: function(){ theimg.data('requesting',false); } }); } }); $('#width').text('$(window).width(): ' + viewPortX); }
This method requires your images/image service be accessible using XMLHttpRequest or you’ll get errors like “XMLHttpRequest cannot load http://placekitten.com/g/1000/582. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.”, but it does guarantee flicker free image swapping.