Experiment No 2

Source Shuffling

Aim

To produce a mobile first solution to the responsive images problem. One that will gracefully fall back to the mobile image when JavaScript is unavailable and prevent the extra resources from loading if the context doesn't warrant their need. As a bonus we want to keep the breakpoint declarations in one place - the CSS.

Ingredients

Method

Resize your browser window and notice how the image changes based on the media queries specified in the CSS loaded into this page (refresh the page when at a small/mobile size). Have a look at your web inspector's resources panel to see exactly what is loaded. Read the original article that outlines the technique.

Note that for this demo I am using this lovely bundled version of Jeremy Keith's Conditional CSS so it differs slightly from the code documented in my article (the approach is the same).

3 Card Monte illustration by @kingsomniac

HTML

<img src="img/small.jpg" data-medium="img/medium.jpg" data-large="img/large.jpg" alt="Responsive images example">

CSS

body:after {
  content: 'global';
  display: none;
}

@media screen and (min-width: 35em) {
  body:after {
      content: 'tablet';
      display:none;
  }
}

@media screen and (min-width: 56em) {
  body:after {
      content: 'desktop';
      display:none;
  }
}
                        

JavaScript

var queries = [
{
    context: 'global',
    callback: function() {
        $('img').each(function(index) {
            var small = $(this).attr('src');
            $(this).attr('src',small);
        });
    }
},
{
    context: 'tablet',
    callback: function() {
        $('img').each(function(index) {
            var medium = $(this).data('medium');
            $(this).attr('src',medium);
        });
    }
},
{
    context: 'desktop',
    callback: function() {
        $('img').each(function(index) {
            var large = $(this).data('large');
            $(this).attr('src',large);
        });
    }
}
];
MQ.init(queries);