CodePen

HTML

            
              <!-- http://css-tricks.com/the-layered-look/ -->

<section class="page-wrap">
  
  <h1>The Layered Look - <span class="nobr">Lazy Loading</span></h1>
  <h2>Better Responsive Images Using Multiple Backgrounds</h2>

<p>
This is a demonstration of "lazy loading" using Caleb Troughton's <a href="http://imakewebthings.com/jquery-waypoints/" target="_blank">jQuery Waypoints plug-in</a>, and enhanced by using CSS3 multiple backgrounds. As you scroll down, each image gets an "hd" class added to it as it appears, triggering a CSS media query to load the high-res background-image over the "lowsrc" version:</p>
<pre rel="jQuery"><code class="language-javascript">
  $('.bg-image').waypoint(function(direction) {
    if (direction === 'down') {
      $(this).addClass('hd');
    }
  }, { offset: 'bottom-in-view', triggerOnce: true });
  <i>/* other offsets: '100%' (image top at viewport bottom),
  '125%' (just beyond the viewport, about to scroll in) */</i></code></pre>
<p>
I've made the offset in this demo 'bottom-in-view' so you can see the images loading. I'd probably want them loaded before the user scrolls to them by using something like '125%'. This approach saves bandwidth for users who don't scroll down, but also gives users the ability to scan the page quickly and see images rather than "loading..." graphics.</p>

<figure>
<div class="crop-height bg-image bg-image-camping"><img height="1920" width="2880" class="scale transparent" src="http://s.cdpn.io/23379/photo-camping_480x320bw.jpg"></div>
<figcaption>
Mobile-first "lowsrc" images all load, then get swapped for high-res as image scrolls into viewport. (Empty cache, and reload page to repeat.)
</figcaption>
</figure>

<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</p>

<h2>Header Level 2</h2>

<ol>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ol>

<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>

<h3>Header Level 3</h3>

<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ul>

<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>

<figure>
<div class="crop-height bg-image bg-image-crayons"><img height="1920" width="2880" class="scale transparent" src="http://s.cdpn.io/23379/photo-crayons_480x320bw.jpg"></div>
</figure>

<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</p>

<h2>Header Level 2</h2>

<ol>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ol>

<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>

<h3>Header Level 3</h3>

<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ul>

<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>

<figure>
<div class="crop-height bg-image bg-image-lemonade"><img height="1920" width="2880" class="scale transparent" src="http://s.cdpn.io/23379/photo-lemonade_480x320bw.jpg"></div>
</figure>

<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</p>

<h2>Header Level 2</h2>

<ol>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ol>

<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>

<h3>Header Level 3</h3>

<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
</ul>

<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>

<figure>
<div class="crop-height bg-image bg-image-sedona"><img height="1280" width="2048" class="scale transparent" src="http://s.cdpn.io/23379/photo-sedona_512x320.jpg"></div>
</figure>

</section> <!-- end .page-wrap -->

            
          
!

↑ Insert the most common viewport meta tag

CSS

            
              .crop-height {
  max-height: 320px;
  height: 320px; /* lt ie8 */
  height: auto;
  overflow: hidden; }

/* base background-image class, specify image below */
.bg-image {
  width: 100%;
  /* prevent scaling past src width (or not) */
  max-width: 1024px;
  /* default background-position */
  background-position: center center;
  /* lt ie 8 */
  -ms-background-position-x: center;
  -ms-background-position-y: center;
  /* scale proportionately */
  background-size: cover;
  /* IE8 workaround - http://louisremi.github.io/background-size-polyfill/ */
  -ms-behavior: url(backgroundsize.min.htc); }

/* images renamed so they're not cached initially */

/* mobile first "lowsrc" - see CSS media queries below for more */

.bg-image-camping {
  background-image: url(http://s.cdpn.io/23379/photo-camping_480x320bw.jpg);
  background-position: center 27%; }

.bg-image-crayons {
  background-image: url(http://s.cdpn.io/23379/photo-crayons_480x320bw.jpg);
  background-position: center 54%; }

.bg-image-lemonade {
  background-image: url(http://s.cdpn.io/23379/photo-lemonade_480x320bw.jpg);
  background-position: center 20%; }

.bg-image-radiocity {
  background-image: url(http://s.cdpn.io/23379/photo-radio_city_480x320bw.jpg);
  background-position: center 80%; }

.bg-image-sedona {
  background-image: url(http://s.cdpn.io/23379/photo-sedona_512x320.jpg); /* b&w */
  background-position: center 21%; }


/* if you want users to be able to easily save your transparent proxy img,
   be sure to manually declare a height and width on the img element itself
   to match the background-image src size (if the placeholder img is smaller),
   otherwise it won't fill the width of the div so user can't always click on it */

img.scale, object.scale {
  display: block; /* corrects small inline gap at bottom of containing div */
  width: 100% /* corrects obscure Firefox bug */
  max-width: 100%;
  /* just in case, to force correct aspect ratio */
  height: auto !important;
  /*width: auto\9; 
  /* ie8+9 - use modernizr instead of this \9 hack */
  /* lt ie8 */
  -ms-interpolation-mode: bicubic;
  /* force a minimum size if img src size is known */
  /* min-height: 320px; /* max-height of .crop-height */
  /* min-width: 480px; /* consistent with image ratio */
  /* optionally center if img src is not as wide as div */
  /* margin: 0 auto; */ }

.invisible {
  visibility: hidden; }

.transparent {
  /* trigger hasLayout for ie */
  zoom: 1;
  /* 0 value in filters retains layout */
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
  opacity: 0; }


/* ==================================================

   MEDIA QUERIES

   .hd class added by jQuery after initial page load
   .multiplebgs class added by modernizr.js

===================================================== */

@media
  /* "mama-bear" - plus any-retina */
  only screen and (min-width : 513px),
  only screen and (-webkit-min-device-pixel-ratio: 1.5),
  only screen and (   min--moz-device-pixel-ratio: 1.5),
  only screen and (     -o-min-device-pixel-ratio: 3/2),
  only screen and (        min-device-pixel-ratio: 1.5),
  only screen and (                min-resolution: 144dpi),
  only screen and (                min-resolution: 1.5dppx) {

  /* no-multiplebgs - if you have a mid-sized image, 
    it's probably sufficient here - it's unlikely a 
    retina display is on an older browser) */

  /* no-multiplebgs high-res fallback */
  .no-multiplebgs .bg-image-camping.hd,
  .no-js .bg-image-camping {
    background-image: url(http://s.cdpn.io/23379/photo-camping_2880x1920.jpg); }

  /* hi-res retina */
  .multiplebgs .bg-image-camping.hd {
    background-image:
      url(http://s.cdpn.io/23379/photo-camping_2880x1920.jpg),   /* high-res on top */
      url(http://s.cdpn.io/23379/photo-camping_480x320bw.jpg); } /* "lowsrc" on bottom */

  /* no-multiplebgs high-res fallback */
  .no-multiplebgs .bg-image-crayons.hd,
  .no-js .bg-image-crayons {
    background-image: url(http://s.cdpn.io/23379/photo-crayons_2880x1920.jpg); }

  /* hi-res retina */
  .multiplebgs .bg-image-crayons.hd {
    background-image:
      url(http://s.cdpn.io/23379/photo-crayons_2880x1920.jpg),   /* high-res on top */
      url(http://s.cdpn.io/23379/photo-crayons_480x320bw.jpg); } /* "lowsrc" on bottom */

  /* no-multiplebgs high-res fallback */
  .no-multiplebgs .bg-image-lemonade.hd,
  .no-js .bg-image-lemonade {
    background-image: url(http://s.cdpn.io/23379/photo-lemonade_2880x1920.jpg); }

  /* hi-res retina */
  .multiplebgs .bg-image-lemonade.hd {
    background-image:
      url(http://s.cdpn.io/23379/photo-lemonade_2880x1920.jpg),   /* high-res on top */
      url(http://s.cdpn.io/23379/photo-lemonade_480x320bw.jpg); } /* "lowsrc" on bottom */

  /* no-multiplebgs high-res fallback */
  .no-multiplebgs .bg-image-radiocity.hd,
  .no-js .bg-image-radiocity {
    background-image: url(http://s.cdpn.io/23379/photo-radio_city_2880x1920.jpg); }

  /* hi-res retina */
  .multiplebgs .bg-image-radiocity.hd {
  background-image:
    url(http://s.cdpn.io/23379/photo-radio_city_2880x1920.jpg),  /* high-res on top */
    url(http://s.cdpn.io/23379/photo-radio_city_480x320bw.jpg); } /* "lowsrc" on bottom */

  /* no-multiplebgs mid-size fallback */
  .no-multiplebgs .bg-image-sedona.hd,
  .no-js .bg-image-sedona {
    background-image: url(http://s.cdpn.io/23379/photo-sedona_1024x640.jpg); } /* sepia */

  .multiplebgs .bg-image-sedona.hd {
    background-image:
      url(http://s.cdpn.io/23379/photo-sedona_1024x640.jpg),  /* mid-sized on top */
      url(http://parkerbennett.com/the-layered-look/img/photo-sedona_512x320.jpg); } /* "lowsrc" on bottom */

  }

/* moving to larger images after the first "bump" we may choose to separate
   width-based adjustments vs. device-based logic. For example, a larger retina
   device can go directly from "lowsrc" default to high-res with no mid-size image */

@media
  /* "papa-bear" - size only */
  only screen and (min-width : 716px) { /* smaller here for demo */

   /* no-multiplebgs mid-size fallback is in MQ above */

  .multiplebgs .bg-image-sedona.hd {
    background-image:
      url(http://s.cdpn.io/23379/photo-sedona_1024x640@2x.jpg), /* on top, higher-res color  */
      url(http://s.cdpn.io/23379/photo-sedona_1024x640.jpg),    /* middle, mid-size sepia */
      url(http://s.cdpn.io/23379/photo-sedona_512x320.jpg); }   /* mobile-first - yes, I'm stacking three */
    }

@media
    /* larger retina device, triggered immediately so interim mid-sized image not needed */
  only screen and (min-device-width : 768px) and (-webkit-min-device-pixel-ratio: 1.5),
  only screen and (min-device-width : 768px) and (   min--moz-device-pixel-ratio: 1.5),
  only screen and (min-device-width : 768px) and (     -o-min-device-pixel-ratio: 3/2),
  only screen and (min-device-width : 768px) and (        min-device-pixel-ratio: 1.5),
  only screen and (min-device-width : 768px) and (                min-resolution: 144dpi),
  only screen and (min-device-width : 768px) and (                min-resolution: 1.5dppx) {

    /* no-multiplebgs mid-size fallback is in MQ above */

    .multiplebgs .bg-image-sedona {
      background-image:
        url(http://s.cdpn.io/23379/photo-sedona_1024x640@2x.jpg), /* on top, higher-res color  */
        url(http://s.cdpn.io/23379/photo-sedona_512x320.jpg); }   /* mobile-first - yes, I'm stacking three */
    }


/* Presentational CSS Below */

/* force a vertical scrollbar to prevent a jumpy page */
html {overflow-y: scroll;}

body {
  background: #eaeaea;
  font-family: sans-serif;
  line-height: 1.3125; }

section {
  display: block;
  width: 80%;
  max-width: 1280px;
  margin: 0 auto 2em;
  padding: 1.5em 3em 3em;
  background: #fff;
  text-align: left; }

figure {
  max-width: 1008px;
  margin: 1.5em auto 1em;
  padding: 8px;
  background: #eaeaea;
  text-align: center; }

figcaption {
  margin: .5em 0;
  color: #999;
  text-align: center;
  font-size: 85%;
  font-style: italic; }

h1 {margin: 0; line-height: 1.125;}

h2 {color: #999; font-weight:300;}

code {
  background: lightyellow;
  padding: 1px .25em;
  font-family: Menlo, Monaco, monospace;
  font-size: 90%;}

pre[rel]{
    position: relative;
    padding: .875em 0 0; }

pre[rel]:before{
    content:attr(rel);
    color:white;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    background:#e18728;
    font-family: sans-serif;
    padding:5px 0;
    text-indent:15px; }

pre code {
  display: block; padding: 1.5em; }

pre code i {
    color: #998;
    font-style: italic; }
            
          
!
? ?
? ?
Must be a valid URL.
+ add another resource
via CSS Lint

JS

            
              $('.bg-image').waypoint(function(direction) {
    if (direction === 'down') {
      $(this).addClass('hd');
    }
  }, { offset: 'bottom-in-view', triggerOnce: true });
            
          
!
Must be a valid URL.
+ add another resource
via JS Hint
Loading ..................