SVG method



.selector { background: url(../path_to_png/apple.png) no-repeat; }
html.svg .selector { background-image: url(../path_to_svg/apple.svg); }

As simple as set background image. However developers should provide graceful degradation for browsers that does not support SVG in CSS. I recommend to use feature detection method (Modernizr) as part of HTML5 Boilerplate.




CSS Media Query and background-size method


.selector { background: url(../path_to_png/apple.png) no-repeat; }
  
@media (-webkit-min-device-pixel-ratio: 2) {
  .selector { background-image: url(../path_to_png/apple@2x.png); background-size: cover; }
}  

Read about background-size options and behavior.




Javascript <img/> source replacing method


jQuery( document ).ready(function(){
  if( 'devicePixelRatio' in window && window.devicePixelRatio == 2 ){
    var img_to_replace = jQuery( 'img.replace-2x' ).get();

    for (var i=0,l=img_to_replace.length; i<l; i++) {
      var src = img_to_replace[i].src;
      src = src.replace(/\.(png|jpg|gif)+$/i, '@2x.$1');
      img_to_replace[i].src = src;
    };
  }
});

// On your HTML code (must provide width or height)
<img src="../path_to_png/apple.png"
     width="200" height="200"
     class="replace-2x" />

Based on CSS Image Replacement for iPhone 4 High-DPI Retina blogpost.




Server-side method with cookies


(function(){
  if( document.cookie.indexOf('device_pixel_ratio') == -1
      && 'devicePixelRatio' in window
      && window.devicePixelRatio == 2 ){
        
    document.cookie = 'device_pixel_ratio=' + window.devicePixelRatio + ';';
    window.location.reload();
  }
})();

// The cookie 'device_pixel_ratio' will be available at server-side

Based on Detecting the iPhone4 and Resolution with Javascript or PHP blogpost.



View project on GitHub Download sources



License

(MIT License) — Copyright © 2012 Egor Khmelev